在我的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模型,使其始终执行这种关联?
触发回调时,控制器已经具有与创建的组相对应的标准实例变量:@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
我假设为您的组给定的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
它应该自动工作。