Nested form and has_many :through

29 views
Skip to first unread message

David M

unread,
Jun 18, 2012, 12:44:53 PM6/18/12
to rubyonra...@googlegroups.com

I have a little sample app where there are 3 models: Members, Groups and Subscriptions. The idea is that member can subscribe to groups.

class Member < ActiveRecord::Base
  has_many
:subscriptions, dependent: :delete_all
  has_many
:groups, through: :subscriptions

  attr_accessible
:email

  validates
:email, presence: true
end

class Group < ActiveRecord::Base
  has_many
:subscriptions, dependent: :delete_all
  has_many
:members, through: :subscriptions

  accepts_nested_attributes_for
:subscriptions

  attr_accessible
:name, :subscriptions_attributes

  validates
:name, presence: true, uniqueness: true
end

class Subscription < ActiveRecord::Base
  belongs_to
:group
  belongs_to
:member

  attr_accessible
:group_id, :introduction

  validates
:group_id, presence: true
  validates
:introduction, presence: true
end

I'm trying to create a form for new groups, and nest the introduction attribute inside.

My controller methods:

def new
 
@group = Group.new
 
@group.subscriptions.build
end

def create
 
@member = Member.first
 
@group = @member.groups.build(params[:group])

 
if @group.save
    flash
[:success] = "Saved"
    redirect_to group_path
(@group)
 
else
    render
:new
 
end
end

But it does not work. It throws the error group_id can't be blank. So I don't know how to assign the new group to the subscription.

Also, the member_id is being created as nil. But as you can see, I'm creating the group from the@member variable, so I think it should be initialized, but it does not.

Anyone can show me the light?

You can see the sample app here: https://github.com/idavemm/nested_form

Pio Ryan Lumongsod

unread,
Jun 19, 2012, 12:11:09 AM6/19/12
to rubyonra...@googlegroups.com
Hi, 

You should use the ruby column name conventions on creating your schema.
ActiveRecord Associations will look for group_id not groups_id unless your specify it on the has_many :through with a :foreign_key => 'groups_id' same with the members_id.

I suggest you alter the name.

thanks

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/qfsC4R2vK80J.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.



--
Pio Ryan S. Lumongsod
Software Engineer/RoR Developer

ETA '03
UP Alpha Phi Omega

David M

unread,
Jun 19, 2012, 11:25:01 AM6/19/12
to rubyonra...@googlegroups.com
Hello Pio,

I have no problem with that, since the names you are seeing are the DB ones. Rails deals with names set at models, and those are in singular.

Thanks!
Reply all
Reply to author
Forward
0 new messages