我正在尝试使用accepts_nested_attributes来创建复杂的表单。根据{{3}}文档,Nested Attributes等,我已经设置了这样的模型:
用户模型:
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>'
我做错了什么?非常感谢提前。
答案 0 :(得分:2)
仅定义属性 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" } ]