2

I have models like that:

class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
end

class Group_Membership
 belongs_to :member, :class_name => 'Person'
 belongs_to :group
end

class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
end

I was just wandering, if a Person wants to join a group, the person will create a group_membership that will need both the id of the Person itself and the Group. If I do a single create button without a form on the group view would be right? And how would be the def create since I will have to pass both ids via build right? Thanks.

Zeroz
  • 125
  • 1
  • 8

1 Answers1

0

More likely you will create a GroupMembership from a Person or Group instance, so only need one id. So when you're talking about using the group view - I assume you mean to include some sort of "add member" form in your show view, so your action for that form might be called create_membership and look something like this:

def create_membership
  @group = Group.find params[:id]
  if @group.group_memberships.create( :member_id => params[:member_id])
    redirect_to @group
  else
     render :action => 'show'
  end
end
smathy
  • 26,283
  • 5
  • 48
  • 68
  • Oh I see, so if I want to create the membership using a button at the `group#show`, I shall add this `def create_membership` to Group_Memberships controller. But how can I create the button on the `group#show` – Zeroz May 18 '11 at 20:21
  • That's a very different question, you can ask that separately - or maybe it'd be worth you heading over to the [Ruby Guides](http://guides.rubyonrails.org/) – smathy May 18 '11 at 20:31
  • Well I did a form: `<%= form_for :group_membership, @:group_membership, :url => { :action => "create_membership" } do |f| %> <%= submit_tag "Create" %>` and put it on the group#show, but always I click the button goes to a new screen to create a new group. Is this error because of my form or because of my controller? – Zeroz May 18 '11 at 20:47
  • Much better to either accept (or not) the answer to **this** question, and then ask a new question with the new problem you have. – smathy May 18 '11 at 22:42
  • Well, that's why I asked if the problem was with my form or with the controller. I can't accept the answer if the problem is with the controller. But if it's not, I can and I will open a new question. – Zeroz May 18 '11 at 23:39