David M
2012-Jun-18 14:26 UTC
Creating an object with a nested has_many :through relationship
I have 3 models that define members, groups and the subscriptions: Member, Group, and GroupMember. class Member < ActiveRecord::Base> has_many :group_subscriptions, class_name: "GroupMember" > has_many :groups, through: :group_subscriptions > attr_accessible :email, :password > end > class Group < ActiveRecord::Base > has_many :member_subscriptions, class_name: "GroupMember" > has_many :members, through: :member_subscriptions > attr_accessible :name > end > class GroupMember < ActiveRecord::Base > belongs_to :group > belongs_to :member > attr_accessible :group_id, :introduction > endIf 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_memberThe 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_attributesIn the new method of the Group controller I have this: def new> @group = Group.new > @group.member_subscriptions.build > endSo 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.saveSo 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? -- 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/-/Focdq7NTIacJ. To post to this group, send email to rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.