Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
238 views
in Technique[技术] by (71.8m points)

ruby on rails - Has many through association

I have two models with a has_many_through association, like this:

class Workspace < ActiveRecord::Base
  has_many :dashboards_workspaces
  has_many :dashboards, through: :dashboards_workspaces
end
class Dashboard < ActiveRecord::Base
  has_many :dashboards_workspaces
  has_many :workspaces, through: :dashboards_workspace
end

When I create a dashboard I have the option to select one or more workspaces and I'm able to get the dashboards with a workspace like this:

Dashboard.joins(:workspaces).all

And I'm getting the workspaces_ids this way:

foo = Dashboard.find(1)
foo.workspaces.id

But I need to only show in the view the dashboards that have the same workspace_id as the current user:

@workspaces = Workspace.where(id: current_user.workspaces)

For example:

Workspace.where(id: current_user.workspaces) = [4]
Dashboard.find(1).workspaces.id = [1, 3]
Dashboard.find(2).workspaces.id = [4]

I need to only show dashboard 2 in the view.

Is there a way that I can accomplish that using a query in my controller?

Thank you so much for your help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will assume that your user model has_many :workspaces if is the case I think you can do something like this:

workspaces_ids = current_user.workspaces.pluck(:id)
dashboards = Dashboard.joins(:workspaces).where(Workspace.arel_table[:id].in(workspaces_ids)).distinct

The above should leave in dashboards all the dashboards that have associations with any of the workspaces inside current_user.workspaces.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...