可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
i have 3 tables - films, films_genres (for connect 2 tables) and genres. In Model film.rb - has_and_belongs_to_many :genres In Model genre.rb - has_and_belongs_to_many :films
So, how I can write this sql code:
SELECT * FROM genres
INNER JOIN films_genres
ON genres
.id = films_genres
.genre_id WHERE (films_genres
.film_id = 1 )
with named_scope in Model film.rb for show all film rolled genres?
回答1:
class Model < ActiveRecord::Base named_scope :by_genre, lambda { |*genres| { :include => :genres, :conditions => [ "genres.id IN (?)", genres.map(&:id) ] } } end Film.by_genre(western, sci_fi).find(:all)
I made this one slightly more complex in order to specify multiple genres as part of your named scope. Hope it helps.
回答2:
In English, what are you trying to pull from the DB? To retrieve the genres for a particular film just do:
@genres = @film.genres
回答3:
chap! I try to pool from the db list of genres connected to the film. And my question is: how I can to do this using named_scome in film.rb Model? I need this for films filter. Link for example: http://clearcove.ca/blog/2008/12/recipe-restful-search-for-rails/#more-218
Databases:
films: id name descr year
films_genres: id film_id genre_id
genres: id name