从InheritedResources #create中检索创建的对象

时间:2012-10-16 16:28:02

标签: ruby-on-rails inherited-resources

在我的Rails应用程序中,我有以下对象:

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

用户可以创建群组。发生这种情况时,我想自动将用户添加到组中。在我的GroupsController中,我有以下内容(扩展InheritedResources):

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

问题是我无法检索super创建的对象。有没有办法做到这一点?或者更好的是,有没有办法更改LockGroup模型,以便始终执行此关联?

2 个答案:

答案 0 :(得分:1)

当触发回调时,控制器已经拥有与创建的组对应的标准实例变量:@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

答案 1 :(得分:0)

我假设你的小组给出的params键是:group。然后,您可以在模型中使用nested_attributes_for选项。然后,您可以在创建操作中设置前过滤器中的那些:

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

或者您在用户初始化时构建组成员资格:

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

它应该自动运作。