在我正在构建的一个小应用程序中,我有一个创建交换的控制器。当用户创建交换时,他们同时是交换的组织者和交换的参与者。user_id
参与者由连接 a和 an的连接表跟踪exchange_id
。user_id
组织者由交换表中的外键跟踪。
我试图找出将自动为交易所组织者创建新会员记录的代码放在哪里。我应该把它放在exchange_controller 的创建动作本身中,还是放在after_filter
由创建动作触发的中?或者也许在别的地方?部分问题是我找不到任何正确使用 after_filter 的好例子(guides.rubyonrails.org 只很少提及它),因此任何指向正确方向的链接也会受到赞赏。
以下是相关型号代码:
app/models/user.rb:
# Returns array of exchanges user is participating in
has_many :participations,
:through => :memberships,
:source => :exchange
# Returns array of exchanges user has organized
has_many :organized_exchanges,
:foreign_key => :organizer_id,
:class_name => "Exchange"
app/models/membership.rb:
class Membership < ActiveRecord::Base
attr_accessible :exchange_id, :user_id, :role
belongs_to :exchange
belongs_to :user
end
app/modles/exchange.rb:
belongs_to :organizer,
:foreign_key => :organizer_id,
:class_name => "User"
has_many :memberships, :dependent => :destroy
has_many :participants,
:through => :memberships,
:source => :user
这是相关的控制器代码:
app/controllers/exchanges_controller.rb:
def create
@exchange = Exchange.new(params[:exchange])
@exchange.organizer_id = current_user.id
if @exchange.save
redirect_to exchange_path(@exchange.id)
else
render 'new'
end
end