I have models User
Course
User.rb
has_many :courses
Course.rb
belongs_to :user
If I have a ActiveRecord_Relation @users
, with a list of user.
How to get a ActiveRecord_Relation @courses
, with a list of course based on @users
I know it can be done @users.each do |user|
one by one. But is there a easier way to do it? like @users.courses
?
您可以使用Ruby的#flat_map方法:
@users.flat_map(&:courses)
flat_map
is a good solution, but won't give you an ActiveRecord::Relation.
If you would like an ActiveRecord::Relation, you could build @courses
like this.
@courses = Course.where(user_id: @users.select(:id))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.