Rails named_scope with has_and_belongs_to_many

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!