undefined method `build_users' with nested models
I've got into trouble with nested attributes.
Here is my Account model :
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
And here is my User model :
class User < ActiveRecord::Base
belongs_to :account
end
As you can see, Account accepts nested attributes for logo, address, and users.
While testing, i can use nested attributes for logo and address, but not for user.
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.开发者_JAVA百科8/gems/activerecord-2.3.5/lib/active_record/attribute_methods.rb:260:in `method_missing'
from (irb):2
Thus, in my views, when i use the nested forms, i got this error back :
User(#69850615730460) expected, got Array(#69850664775200)
Any help would be appreciated.
Thanks.
EDIT : view
<%= 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 -%>
use
a.users.build() #as Account has many users
精彩评论