简体   繁体   中英

Table Join in Rails Active Record

I have a film model

class Film < ActiveRecord::Base
  has_many :film_genres
  has_many :genres, through: :film_genres 
end

a genre model

class Genre < ActiveRecord::Base
  has_many :film_genres
  has_many :films, through: :film_genres
end

and then I have my filmGenre model

class FilmGenre < ActiveRecord::Base
  belongs_to :film
  belongs_to :genre
end

Im try to get a list of films in the controller under a particular Genre, but cant seem to get a join to work.

  def show
    @films = ## need a join / select here to fetch all films with Genre.id of 4
  end

Use includes to join the genres table and then you can reference it in the where conditions:

@films = Film.includes(:genres).where(genres: {id: 4})

Alternatively, it might be easier to get all the films for genre 4 by starting with the Genre model:

@films = Genre.find(4).films

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM