Active Record Querying belong_to
I have the two following models associated:
class Post < ActiveRecord::Base
belongs_to :language
end
class Language < ActiveRecord::Base
has_many :posts
end
From a view I have a link to filter the posts by language:
<div id="english"><%= link_to "English", {:controller => 'posts', :action => 'search_result', :language => "english"} %></div>
The model language has a variable name:string which is the one i am using to make the active record query.
The doubt i have is how i can make this query from the post controller to retrieve the right posts which has a field: language.name == "english".
I tried this:
@posts = Post.all(:conditions => ["language.name = ?", params[:language]])
and also this:
@posts = Post.where(:language.name => params[:language])
Hope i have explained well the issue, i am a quite newbie yet. Ah! i would also know wha开发者_如何学Got would it be better in this case to use: "all" or "where" ??. Thanks a lot in advance.
You need to do a join: http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables
If I have understood your models/database structure correctly, the ActiveRecord call should looks something like:
Post.joins(:language).where('languages.name' => params[:language])
Hope that helps.
PS. The where
call is the preferred method these days.
精彩评论