PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to accumulate results from has_many relationship?

 October 21, 2022     activemodel, activerecord, has-many, ruby-on-rails, ruby-on-rails-4     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing