[英]Ruby on Rails: application wide filtering with id in every model
I am doing this software for clubs where people can just sign in and add scores, players, teams etc. Now I of course have many clubs and for every model there is club_id column to identify that club. 我正在为人们可以登录并添加得分,球员,球队等的俱乐部使用此软件。现在我当然有很多俱乐部,并且对于每种型号,都有club_id列来标识该俱乐部。 Is there some easier way to check for current club than writing something like this:
有没有比写这样的东西更简单的方法来检查当前俱乐部:
News.where("club_id = ?", @club_id)
I found it too hard to abstract this proplem so much that I could find any answer. 我发现很难抽象这个问题,以至于找不到任何答案。
One way would be to make some basic class for your models: 一种方法是为模型建立一些基础类:
class ClubStuff < ActiveRecord::Base
self.abstract_class = true # <--- don't forget
default_scope { where(club_id: Thread.current[:club_id]) }
end
and make your models out of it: 并从中制作模型:
class News < ClubStuff
Then: 然后:
# in ApplicationController
before_filter { Thread.current[:club_id] = params[:club_id] }
I hope you got the idea. 我希望你有主意。
Why create an extra id (club_id) when there is a default id attribute in every model in RoR? 当RoR中的每个模型都有默认的id属性时,为什么还要创建一个额外的id(club_id)? You can use this code
您可以使用此代码
News.find(id).
News.find(id)。
If you still insist, then an alternative code is: 如果您仍然坚持,那么替代代码是:
News.find_by_club_id(@club_id)
News.find_by_club_id(@club_id)
Well you could write some before filters in your controller. 好吧,您可以在控制器中的过滤器之前写一些。 Using your
Team
example: 使用您的
Team
示例:
class TeamController < AC
before_filter :get_club, :only => [ :index ] # you can limit the filter to methods
def index
# because of the before filter you can access club here
@teams = @club.teams
end
# ...
private
def get_club
@club = Club.find(params[:club_id])
end
end
This behavior could be moved into a module as well. 此行为也可以移到模块中。 See here for more information on filters.
有关过滤器的更多信息,请参见此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.