Rails JOIN TABLES
I have the following SQL QUERY:
SELECT articles.name, articles.price, users.zipcode FROM articles INNER JOIN users ON users.id = articles.user_id WHERE vectors @@ to_tsquery ('crime') ORDER BY articles.price ASC
And I would like to write it inside find method from ActiveRecord class named "Articles" (articles are owned by user). Basically I want to search for articles and access the zipcode profile from User (user has_many Articles)
I wrote the following version, but I'm not sure if it works because I am not getting any information about custom zipcode in the answer.
a = Article.find (: all ,: conditions => "vectors @@ to_tsquery ('crime')" ,: joins =>: user ,: order =>: price ,: include =>: user)
But I have no idea how to access the zipcode information. how can i access this information? is this the right approach?
Hello,
Victor
source to share
If you linked Articles
and Users
as you say above, it should be pretty simple:
@articles = Article.find(:all, :conditions => "…", :include => :user)
Then, in your opinion, you can do:
<ul>
<% for each article in @articles do %>
<li><%= article.user.zipcode %></li>
</ul>
<% end %>
This works because Rails creates a property for the parent object ( User
) in the model ( Article
) - you can read more about this in the API docs . This even works without the "include" key above, but excluding it would mean querying the database at every step of the loop.
source to share