vendredi 20 mars 2015

Many to many realationship and join in rails 3

I have following three models



class Rating < ActiveRecord::Base
belongs_to :user
belongs_to :book
end

class User < ActiveRecord::Base
attr_accessible :name, :dob, :mobile
has_many :books, :through => 'ratings'
end

class Book < ActiveRecord::Base
attr_accessible :book_name, :author, :pages
has_many :users, :through => 'ratings'
end


Now I have to find all the "book_name"s of each book which is related the respective user and store it in the array.


Here is code



@book_names = []
@books = Rating.find(:all, 'user_id = ?', current_user.id)
@books.each do |book|
book_info = Book.find(book.id)
@book_names << book_info.book_name
end


Is there any other way for the same or join method.


Aucun commentaire:

Enregistrer un commentaire