gpt4 book ai didi

ruby-on-rails - accepts_nested_attributes_for 未定义方法错误

转载 作者:太空宇宙 更新时间:2023-11-03 16:09:03 24 4
gpt4 key购买 nike

我正在尝试使用 accepts_nested_attributes 来创建一个复杂的表单。基于Nested Attributes文档,examples等,我已经像这样设置了模型:

用户模型:

require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :first_name, :last_name, :email, :password,
:password_confirmation, :ducks_attributes

has_many :ducks, :class_name => 'Duck'
accepts_nested_attributes_for :ducks
.
.
.
end

鸭模型:

class Duck < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end

但是当我尝试访问控制台中的嵌套属性时,我得到了

ruby-1.9.2-p290 :003 > User.first.ducks_attributes
NoMethodError: undefined method `ducks_attributes' for #<User:0x007ffc63e996e0>
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activemodel-3.0.9/lib/active_model/attribute_methods.rb:392:in `method_missing'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/activerecord-3.0.9/lib/active_record/attribute_methods.rb:46:in `method_missing'
from (irb):3
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:44:in `start'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands/console.rb:8:in `start'
from ~/.rvm/gems/ruby-1.9.2-p290@rails3tutorial/gems/railties-3.0.9/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

我做错了什么?非常感谢。

最佳答案

只定义了属性writer

class User < ActiveRecord::Base
has_many :ducks
accepts_nested_attributes_for :ducks
end

class Duck < ActiveRecord::Base
belongs_to :user
end

# This works:
User.first.ducks_attributes = [ { :name => "Donald" } ]

# This is more common (attributes posted from a form):
User.create :ducks_attributes => [ { :name => "Donald" }, { :name => "Dewey" } ]

关于ruby-on-rails - accepts_nested_attributes_for 未定义方法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7590458/

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