Chinmay235
Chinmay235

Reputation: 3414

Ruby has_many model association not working

Here is two table properties and property_images I want to associate both table.

properties

id
name
status
other-columns-here

property_images

id
property_id
image
status

Here is code -

class Property < ActiveRecord::Base
  has_many :property_images, dependent: :destroy
end


class PropertyImage < ActiveRecord::Base
  belongs_to :property
end

users_controller.rb

def index
   @properties = Property.order('id');
   render html:@properties #13 properties coming
end

I have tried to has_many association but only coming properties data. Please help me

Upvotes: 0

Views: 63

Answers (5)

Raj Kumar
Raj Kumar

Reputation: 61

try the following controller and view

# users_controller.rb
def index
   @properties = Property.includes(:property_images).order(:id)
end

In your view, you need to put each for property_images not property,

#properties.html.erb
<% @properties.each do |p| %>
   <% p.property_images.each do |image| %>
      <%= image.id %>
   <% end %>
<% end %>

Upvotes: 0

karina
karina

Reputation: 805

I think you need to use :include => :property_images to eager load when you query for properties

You would put this in the params for the query. May just need to use Property.find

Upvotes: 0

thanhnha1103
thanhnha1103

Reputation: 1055

Try this controller

# controller.rb
def index
   @properties = Property.includes(:property_images)
end

and view

#view.html.erb
<% @properties.each do |p| %>
   <% p.property_images.each do |image| %>
      <%= image.id %>
   <% end %>
<% end %>

Upvotes: 1

Waclock
Waclock

Reputation: 1726

The two models are correctly associated, however, if you want to access the property_images without making any extra queries in the view, you can do so by the following three methods:

@properties = Property.includes(:property_images)

@properties = Property.eager_load(:property_images)

@properties = Property.preload(:property_images)

You can read more about eagerloading/preloading in the following blog

You can also add a scope to your property model, to access them more easily (and save a little bit of your time by not repeating the same code over and over again).

In your property model add the following

scope :with_property_images,-> {joins(:property_images)}

Then you can access properties with preloaded images by calling said scope.

Update: If you're using rails 4, the scope must be wrapped inside a lambda. I've updated the scope code, it should work on both rails 3 and 4.

Upvotes: 1

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

Try the below:

def index
   @properties = Property.includes(:property_images).order('id');
   #render html:@properties #13 properties coming
end

For viewing images:

 <% @properties.each do |p| %>
   <% p.each do |image| %>
      view image & data
   <% end %>
<%end%>

Upvotes: 0

Related Questions