views:

655

answers:

3

Hi, 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?

A: 

In English, what are you trying to pull from the DB? To retrieve the genres for a particular film just do:

@genres = @film.genres
chap
A: 

Hi, 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

Yud
Sounds like you're trying to have some kind of dynamic named_scope, but I'm still not quite sure why.Have you looked at the railscasts on the subject? http://railscasts.com/episodes/108-named-scope and http://railscasts.com/episodes/112-anonymous-scopes
chap
+3  A: 
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.

Brian Guthrie
Big thanks, Brian, works fine!
Yud
Thanks for this!
Joe