Nested form and has_many :through

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

https://lh4.googleusercontent.com/-sOcmxtSyn0E/T99a4R2vlLI/AAAAAAAAACo/d1uypAxeBYo/s1600/Captura+de+pantalla+2012-06-18+a+la(s)+18.27.34.png

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 [email protected] 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

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

On Tue, Jun 19, 2012 at 12:44 AM, David M [email protected] wrote:

has_many :groups, through: :subscriptions
has_many :members, through: :subscriptions
belongs_to :group
I’m trying to create a form for new groups, and nest the introduction attribute

redirect_to group_path(@group)

“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 [email protected]
To unsubscribe from this group, send email to
[email protected]
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

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!

El martes, 19 de junio de 2012 06:11:09 UTC+2, [email protected] escribi: