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