gpt4 book ai didi

ruby-on-rails - 未定义的方法 `build' 为 nil :NilClass rails

转载 作者:行者123 更新时间:2023-12-04 03:36:36 24 4
gpt4 key购买 nike

我认为正在发生的是我认为的 :pledge 属性(:amount 和 :frequency)没有传递给 Controller ​​中的新操作。另外,我知道我的质押属性没有保存,这可能是因为在调用 @user 时 promise_id 为零。

新的.html.erb

<%= form_for @user, url: pledge_path, controller: 'user', action:     'create', method: 'post' do |f| %>
<%= f.label :user_name %>
<%= f.text_area :user_name %>
<%= f.label :email %>
<%= f.text_area :email%>
<%= f.label :address %>
<%= f.text_area :address %>
<%= f.fields_for(:pledge) do |b| %>
<%= b.label :amount %>
<%= b.text_area :amount %>
<%= b.label :frequency %>
<%= b.text_area :frequency %>
<%= b.submit 'I also want o pledge' %>
<% end %>
<%= f.submit 'I just want to sumbit my info' %>

<% end %>

promise 文件
class Pledge < ActiveRecord::Base
belongs_to :user
validates_presence_of :user

end

用户名
class User < ActiveRecord::Base
has_many :pledges, foreign_key: "pledge_id"
accepts_nested_attributes_for :pledges
attr_accessor :pledges

end

模式文件
ActiveRecord::Schema.define(version: 20150318161827) do

create_table "pledges", force: :cascade do |t|
t.integer "frequency"
t.float "amount"
t.integer "user_id"
end

add_index "pledges", ["user_id"], name: "index_pledges_on_user_id"

create_table "users", force: :cascade do |t|
t.string "user_name"
t.string "email"
t.string "address"
t.integer "pledge_id"
end

end

用户 Controller .rb
class UserController < ApplicationController
def new
@user = User.new
@user.pledges.build
end

def create
if params[:commit] == 'I just want to sumbit my info'
User.create(user_params)

elsif
@pledge = Pledge.new(params[:pledge])
@pledge.save
@user = User.create(pledge_params)
end
redirect_to thank_you_path

end
def pledge_params
params.require(:user).permit(:email, :user_name, :address,
pledge_attributes: [:id, :amount, :frequency])
end

def user_params
params.require(:user).permit(:email, :user_name, :address)
end
end

在此先感谢您的任何建议!

最佳答案

信息来自 here在像你这样的情况下对我很有帮助。

所以在Sontya的代码中你需要改变@user.pledges.build@user.build_pledges .

虽然,我认为你解决了你的问题,但我做这个答案是为了帮助任何将搜索此信息的人。

关于ruby-on-rails - 未定义的方法 `build' 为 nil :NilClass rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129586/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com