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.

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

  attr_accessible :email

  validates :email, presence: true

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

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

  attr_accessible :group_id, :introduction

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

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

My controller methods:

def new
  @group =

def create
  @member = Member.first
  @group =[:group])

    flash[:success] = "Saved"
    redirect_to group_path(@group)
    render :new

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:


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.


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.