I have an index page that I want to show all the users' profile and their associated photos. I'm using the plugin Paperclip for the photos. In the Profiles controller, I have the instance variable @profile but it shows me the table in the profiles table only and not the photos table.
@profile = Profile.find(:all, :include => :photos,
:joins => "INNER JOIN photos ON photos.profile_id = profiles.id")
The models are shown below:
class Profile < ActiveRecord::Base
has_many :photos
end
class Photo < ActiveRecord::Base
belongs_to :profile
end
What I want to be able to show in the View is something like:
Ans: Joining two tables in SQL can be done in four major ways: Inner Join (returns rows with matching columns), Left Join (ALL records in the left table and matching records in the right table), Right Join (ALL records in the right table and matching records in the left table), and Union (removes duplicates).
Ruby on Rails ActiveRecord Query Interface Joins joins() allows you to join tables to your current model. For ex. User.joins(:posts)
Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);
I've edited my answer to reflect your extra comments.
First of all, you shouldn't need the :joins
parameter; :include => :photos
should handle the join "behind the scenes" for you.
Here's one way to do what you're asking about.
(in the models)
class Profile < ActiveRecord::Base
has_many :photos
has_one :primary_photo, :class_name => "Photo", :conditions => {:primary => true}
end
(in the controller)
@profiles = Profile.find(:all, :include => :primary_photo)
(in the view)
<% @profiles.each do |profile| %>
Name: <%= profile.name %>
Age: <%= profile.age %>
Photo: <%= image_tag profile.primary_photo.url %>
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With