开发者

Another rails nested form question

开发者 https://www.devze.com 2023-01-08 10:54 出处:网络
Trying to perform a nested object form. The page loads with no errors, but when I send it, no information gets saved to the organization model开发者_如何学运维.

Trying to perform a nested object form. The page loads with no errors, but when I send it, no information gets saved to the organization model开发者_如何学运维.

The SQL call says this ..

Parameters: {"commit" => "save", "action"=>"update","_method"=>"put",  "organization"=>{"likes_snacks"=>"0"}, ..

Which is right. The 1 and 0 can be changed properly by flipping on and off the checkbox. But that information is just not saved to the database I guess. Any ideas?

HAML:

- form_for @user do |f|
  = f.label :username
  = f.text_field :username
.clear
  - fields_for :organization do |org| unless @user.organizations.empty?
    = org.label :likes_snacks, 'Like snacks?'
    = org.check_box :likes_snacks
= f.submit 'save', {class => 'button'}

CONTROLLER:

def edit
  @user = current_user
  @organization = current_user.organizations.first
end

MODELS:

ORGANIZATION.RB:

has_many  :users, :through => :organizations_users

USER.RB:

has_many  :organizations, :through => :organizations_users


It seems like you can save the parent attributes but not the child attributes.

To make child attributes accessible through a nested forms you’ll need to add the “#{child_class_name}_attributes” to the attr_accessible method in your parent class.(Only if use attr_accessible in parent model)

So your parent model should look like this:

class User < ActiveRecord::Base
  attr_accessible :username, :organizations_attributes
  accepts_nested_attributes_for :organizations
end

Also, If you don’t use attr_accessible in your parent model this is not necessary.


I think the interesting part here is the linker table :organization_users.

The accepted answer on this so question says you need

form_for @user do |f|
  f.fields_for :organization_users do |ff|
    ff.fields_for :organization


Also go through this one of the great article about accepts_nested_attributes_for which is very useful when you want a single form to cater to multiple models.

http://currentricity.wordpress.com/2011/09/04/the-definitive-guide-to-accepts_nested_attributes_for-a-model-in-rails-3/

Hope you will like this.

Thanks

Rameshwar

0

精彩评论

暂无评论...
验证码 换一张
取 消