0

I have an api. In that api is a basecontroller that all other controllers inherit from. The basecontroller handles authentication and whether or not the API is on at all, etc.

There are users, and users can belong to a group. Users table has a group_id column.

I'm trying to introduce a new feature, whereby a select on the settings page for admin controls which users are shown from what groups. If an option is selected, only users from that group should be shown by the api.

I could go into each controller (there is one controller for each of a few different tasks - getting all users info, just active_users ids, a single users information, etc) and add the extra statement to each

if !settings.api_group.nil?
  #add the additional where("group_id = ?, settings.group_id)

but that seems like a lot of repeating myself (doing it in 8 different places)

Is there some way to add something to the basecontroller that says:

if this setting option is not nil, only return user information if they are in this group

?

Thanks

4

2 に答える 2

1

メソッドを BaseController に追加し、この制限が必要な各アクションで呼び出すことができます。このようなもの:

base_controller.rb:

protected

def filtered_users
  if settings.api_group
    User.where(:group_id => settings.group_id)
  else
    User.scoped
  end
end

そして、それを継承するコントローラーでは:

def index
  @users = filtered_users
end

このようにして、フィルタリングを 1 か所で定義するだけです。後で変更する必要がある場合は、1 か所だけ変更する必要があります。実際には関係を返すため、次のように句をfiltered_users追加するなどしてクエリを変更し続けることができます。.where

@users = filtered_users.joins(:posts).where('posts.created_at > ?', 1.week.ago)

于 2013-01-16T20:26:28.623 に答える
0

参考までに、私の答えは、最初の投稿にあるはずだと思っていたものとまったく同じでした。よりDRYなソリューションがあればいいのですが、最終的には次のようなことをしました:

ユーザーモデルで

def find_in_api_group
  # NOTE settings.api_group is a string => "1,2,4"
  if settings.api_group.nil? || settings.api_group.blank?
    where("") # THERE HAS TO BE BETTER WAY OF SAYING THIS WITHOUT INTERRUPTING THE CHAIN
  else
    where("group_id IN (?)", settings.api_group)
  end
end

さまざまなコントローラーで

user = User.find_in_api_group 
#then chain various error tests and additional activeRecord statement
于 2013-01-17T17:37:07.973 に答える