0

在我的 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 模型,使其始终执行这种关联?

4

2 回答 2

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
于 2012-10-17T00:51:49.100 回答
0

我假设为您的组提供的 params 键是 :group。然后您可以在模型中使用nested_attributes_for 选项。然后,您可以在 create 操作的 before 过滤器中设置它们:

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

它应该自动工作。

于 2012-10-16T17:00:08.490 回答