开发者

Ruby on Rails, Model Joins

I have 2 models:

class Video < ActiveRecord::Base
belongs_to :categories, :foreign_key => "category", :class_name => "Category"
end

class Category < ActiveRecord::Base
has_many :videos
end

This is fine so far, in my videos controller for the index page I have:

def index
@videos = Vid开发者_如何学JAVAeo.all(:joins => :categories)

etc, etc
end

The above produces the following SQL Query: SELECT videos.* FROM videos INNER JOIN categories ON categories.id = videos.category

Which is fine up to a certain point, basically I need to get the category name (a field in that table) that way I don't have to do another call in the view to get category name based on the category id. Any ideas?

Thank you, and yes I am new to ruby, I tried reading the API but couldn't find much help there.


If think the association in your Video class is set up incorrectly. It should be:

class Video < ActiveRecord::Base
  belongs_to :category
end

You can do @videos = Video.all(:include => :category). This will retrieve the video and associated category records using a single SQL statement.

Incidentally, your :class_name option on the belongs_to association is redundant because ActiveRecord will already have automatically inferred the class name from the association name. You should only use this option if you want to have an association name that is different from the underlying class e.g. authors/Person.


join_condition = " ,categories where INNER JOIN categories ON categories.id=videos.category"

@videos = Video.all(:joins => join_condition)

try this

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜