我想通过一行代码获取所选boards
的所有projects
的列表:
boards = projects.boards
怎么做?
目前,我在每个项目上单独进行迭代,获取其电路板并在数组中累积结果(下面的代码)
class Project < ActiveRecord::Base
has_many :boards
end
class Board < ActiveRecord::Base
belongs_to :project
end
class Account < ActiveRecord::Base
has_many :projects
end
projects = @account.projects.where("SOME_CONDITION")
# my current code:
boards = []
projects.each do |project|
boards << project.boards
end
# wanted code:
boards = projects.boards # <--- How to achieve it?
答案 0 :(得分:3)
如果我做得对,你想拥有一个帐户项目的董事会。您需要为模型添加更多行。
1
class Project < ActiveRecord::Base
has_many :boards
belongs_to :account
end
2
class Board < ActiveRecord::Base
belongs_to :project
belongs_to :account, through: project
end
3
class Account < ActiveRecord::Base
has_many :projects
has_many :boards, through: :projects
def projects_boards(project_ids)
self.boards.where(boards.project_id: project_ids)
end
end
然后就这样称呼它:
boards= @account.boards
编辑以满足您的需求:
boards = @account.projects_boards(projects.map(&:id))
答案 1 :(得分:0)
使用此语法
projects = @ account.projects.where(&#34; SOME_CONDITION&#34;)。last.boards
答案 2 :(得分:0)
您可以使用Project.a_scope.includes(:boards).each do |project|
projects.boards.do_something
end
AR语句来获取与每个项目相关的所有电路板
select * from projects where ...
将使用两个SQL查询来获取与所需项目相关的所有板。
select * from boards where boards.project_id in (1,2,3,4...)
project_ids = Project.a_scope.pluck(:id)
boards = Board.where(id: project_ids)
如果你想要的只是你自己可以做的那个板子列表
{{1}}
答案 3 :(得分:0)
class Project < ActiveRecord::Base
has_many :boards
end
class Board < ActiveRecord::Base
belongs_to :project
end
class Account < ActiveRecord::Base
has_many :projects
has_many :boards, through: :projects
end
我们只是说
SOME_CONDITION = "projects.state = 'active'"
请使用:
@account.boards.where(SOME_CONDITION)