2009-02-12 155 views
0

我在我的模型中使用繼承。一個事件有不同的類型:繼承控制器

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 =會話[:USER_ID] ... ,...在活動,遊戲和訓練的控制器中的每個創建方法中

有人知道如何處理這個最好的。

感謝

+0

不是你的問題頂部的繼承語法倒退嗎? (我假設他們都繼承了事件?) – 2009-02-12 21:36:39

+0

你100%正確 – Tarscher 2009-02-13 09:01:03

回答

0

不要使用game.user_id,而不是你能做到這一點!

associations guide也可能有幫助。

3

也許你正在尋找駐留在你的ApplicationController一個的before_filter?然後在每個控制器中,可以將before_filter設置爲在創建操作上運行。您的其他控制器

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

重複過:

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 
+0

很高興,當新的答案進來時,stackoverflow顯示你一個提醒,因爲我只是在輸入相同的解決方案。 – 2009-02-12 17:16:19

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