控制器中的继承

时间:2009-02-12 15:58:11

标签: ruby-on-rails ruby

我在模型中使用继承。事件有不同的类型:

Event < activity
Event < training
Event < game

我想将会话数据设置为每个事件类型,如

game.user_id = session[:user_id]
training.user_id = session[:user_id]
activity.user_id = session[:user_id]

我想避免在活动,游戏和培训的控制器中的每个创建方法中编写@ game.user_id = session [:user_id],...,...

有人知道如何做到最好。

由于

3 个答案:

答案 0 :(得分:3)

也许您正在寻找驻留在ApplicationController中的before_filter?然后在每个控制器中,您可以将before_filter设置为在创建操作上运行。

ApplicationController
  def set_user_ids
    game.user_id = session[:user_id]
    training.user_id = session[:user_id]
    activity.user_id = session[:user_id]
  end
  ...
end

OneController < ApplicationController
  before_filter :set_user_ids, :only => [:create]
  ...
end

TwoController < ApplicationController
  before_filter :set_user_ids, :only => [:create]
  ...
end

答案 1 :(得分:0)

不要使用game.user_id,而是可以这样做:

game = current_user.games.build(params[:game])
if game.save
  # do something
else
  # do something else
end

重复其他控制器!

associations guide也可能会有所帮助。

答案 2 :(得分:0)

通常,您会希望使用Rails提供的内置范围。只是为了充实@Radar已发布的内容:

class ApplicationController < ActionController::Base
  before_filter :find_current_user

  private
    def find_current_user
      @current_user = User.find( session[:user_id] )
    end
end

class EventsController < ApplicationController
  def create
    @event = @current_user.events.build( params[:event] )
    @event.save!
  end
end

这假设您已在模型中设置关联:

class User
  has_many :events
end

class Event
  belongs_to :user
end

如果您需要限制用户可以查看或编辑的内容,这也是一种非常方便的机制:

class EventsController < ApplicationController
  def index
    @events = @current_user.events # only fetch current users events
  end

  def update
    @event = @current_user.events.find( params[:id] ) # can't update other user's events
    @event.update_attributes!( params[:event] )
  end
end