Reputation: 11
I have to make a join query on 2 tables in ruby on rails. It works fine, but object doesn't contains column in 2 tables that I have joined.
In controllers
@posts = Posts.select("*").joins(:users).joins(:categories).all
In view
<% @posts.each do |p| %>
<%= p.inspect %>
<% end %>
Result in view
Doesn't have column username in table user, etc...
Upvotes: 0
Views: 150
Reputation: 1445
Actually it should work.
Although the inspect only shows you the Post attributes, After doing this:
@posts = Post.select("*").joins(:users).joins(:categories).all
try to get to a specific attribute of a user
<% @posts.each do |p| %>
<%= p.first_name %> # or any other user attribute
<% end %>
and it should show you the users first name.
if its not working you could do:
@posts = Post.select("posts.*, users.*, categories.*").joins(:users).joins(:categories).all
select(...HERE...)
are in their plural form, because its the name of the tables in the DB itself.Upvotes: 0
Reputation: 18647
The object that comes after using the join query actually contains the data of both the tables, butt will not display it while giving puts or inspect.
we can directly call the attributes of the users table from the @posts object like,
<%= @posts.first.user_name %> or any other field.
Upvotes: 1
Reputation: 1424
Please try :
@posts = Posts.select("users.username, users.column2, users.column-n, categories.name, categories.column2, categories.column-n*").joins(:users, :categories).all
Upvotes: 0