I have 3 models that define members, groups and the subscriptions:
Member,
Group, and GroupMember.
class Member < ActiveRecord::Base
belongs_to :group
belongs_to :member
attr_accessible :group_id, :introduction
end
If I want to create a subscription of an existing member to an existing
group, I do this in the create method of the GroupMember controller,
after
getting the member and group at first:
@group_member = GroupMember.new(params[:group_member].merge(group_id:
@group.id))
@member.group_subscriptions << @group_member
The form just contains an attribute called introduction. This works
well.
Now, how can I create a Group with a nested subscription for the current
user who is filling in the form?
I have tried adding this to the Group model:
accepts_nested_attributes_for :member_subscriptions, :members
attr_accessible :name, :member_subscriptions_attributes
In the new method of the Group controller I have this:
def new
@group = Group.new @group.member_subscriptions.build
end
So in the new template I added this:
<%= f.fields_for :member_subscriptions do |ms| %>
<%= render partial: "group_members/form", locals: { f: ms } %>
<% end %>
The form shows correctly with the introduction textarea, and it
validations
are working. But when all data is fine and I submit the form, the new
template is displayed again with no errors, although I have achieved to
get
the actual error:
[:group_id, “can’t be blank”]
That’s because in my create method I have this (simplified):
@group = Group.new(params[:group])
@group.save
So the problem is that the subscription is being created from the group,
when I think it should be created from the member side
(GroupMember.member_id is not accessible to the member for security
reasons, as the member could create a subscription for another member,
only
group_id is accessible for him).
How can I create the nested subscription?