我遇到了嵌套属性的问题。
这是我的帐户模型:
class Account < ActiveRecord::Base
has_many :products
has_many :blogs
has_many :openings
has_many :users
has_one :logo, :class_name => "AccountPicture"
has_one :address, :class_name => "AccountAddress"
has_and_belongs_to_many :options
accepts_nested_attributes_for :logo, :allow_destroy => true
accepts_nested_attributes_for :address, :allow_destroy => true
accepts_nested_attributes_for :users, :allow_destroy => true
end
这是我的用户模型:
class User < ActiveRecord::Base
belongs_to :account
end
如您所见,Account接受徽标,地址和用户的嵌套属性。
在测试时,我可以使用徽标和地址的嵌套属性,但不能用于用户。
a = Account.new
=> #<Account id: nil, hostname: nil, subdomain: nil, name: nil, description: nil, base_line: nil, footer: nil, phone_number: nil, mobile_number: nil, email_address: nil, created_at: nil, updated_at: nil>
# building the address works fine
>> a.build_address
=> #<AccountAddress id: nil, account_id: nil, country: nil, state: nil, county: nil, city: nil, suburb: nil, zipcode: nil, street: nil, streetno: nil, longitude: nil, latitude: nil, error_code: nil>
# building the users fails
>> a.build_users
NoMethodError: undefined method `build_users' for #<Account:0x7f6862a5f948>
from /usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing'
from (irb):2
因此,在我看来,当我使用嵌套表单时,我收到了这个错误:
User(#69850615730460) expected, got Array(#69850664775200)
任何帮助都将不胜感激。
感谢。
编辑:查看
<%= error_messages_for :account %>
<% form_for :account, :url => accounts_path do |f| -%>
<fieldset>
<legend>Account</legend>
<%= label_tag 'name' %>
<%= f.text_field :name, :class => "textbox" %>
</fielset>
<% f.fields_for :users do |user_form| %>
<fieldset>
<legend>User</legend>
<%= label_tag 'email' %>
<%= user_form.text_field :email, :class => "textbox" %>
<%= label_tag 'password' %>
<%= user_form.password_field :password, :class => "textbox" %>
<%= label_tag 'password_confirmation' %>
<%= user_form.password_field :password_confirmation, :class => "textbox" %>
</fieldset>
<% end -%>
<div class="buttons">
<%= submit_tag 'Submit', :class => "button" %>
</div>
<% end -%>
答案 0 :(得分:6)
使用
a.users.build() #as Account has many users