Issue
I want to get a list of all boards
from selected projects
with just one line of code:
boards = projects.boards
How to do it?
Currently I iterate individually over each project, get its boards and accumulate results in array (code below)
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?
Solution
If I am getting it right, you want to have boards for an account's projects. You need to add few more lines to your models.
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
And then just call it like this:
boards= @account.boards
Edited call to suit your needs:
boards = @account.projects_boards(projects.map(&:id))
Answered By - Devd Answer Checked By - Timothy Miller (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.