Question

In my Rails app, I have the following objects:

Group: has_many users through group_membership
GroupMembership: belongs_to user, belongs_to group
User: has_many groups through group_membership

Users can create groups. When this happens, I want to automatically add the user to the group. In my GroupsController, I have the following (extending InheritedResources):

super do |success, failure|
  if success
    GroupMembership.create(:user_id => current_user, :group_id => ???)
  ...
end

The problem is I cannot retrieve the object that super created. Is there a way to do this? Or better, is there a way to change the LockGroup model so that it always performs this association?

Was it helpful?

Solution

When the callback is fired, the controller already has the standard instance variable corresponding to the created group: @group !!

class GroupController < InheritedResources::Base

  def create
    super do |success, failure|
      if success
        GroupMembership.create(:user_id => current_user, :group_id => @group.id)
      ...
    end
  end

end

OTHER TIPS

I assume the params key given for your group is :group. Then you can used the nested_attributes_for option in the model. Then you can set those in a before filter from the create action:

class User < ActiveRecord::Base
  accept_nested_attributes_for :group_membership
end

# on your controller
before_filter :add_user, :on => [:create]

def add_user
  params[:group][:group_membership_attributes] = {}
  params[:group][:group_membership_attributes][:user] = current_user
end

or you build the group membership on user initialize:

class User < ActiveRecord::Base
  def after_initialize
    build_group_membership
  end
end


# on your controller
before_filter :add_user, :on => [:create]

def add_user
  params[:group][:user] = current_user
end

and it should automagically work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top