0

I'm trying to list a user's wanted ads in their show page when they access /users/:id.

In my controller I have:

 def show
    @user = User.find(params[:id])
    @wanted_ads = WantedAd.where(:user_id => params[:id])

And in my show.html.erb I have:

<%= @wanted_ads %>  

Binding.pry says @wanted_ads is nil. On the actual page I get #<ActiveRecord::Relation:0x007fa3b5a93408>. This is seemingly a simple thing I'm trying to do -- what am I missing?

jenno
  • 71
  • 1
  • 2
  • 7

3 Answers3

2

The where function returns a ActiveRecord::Relation. So, you can call first to get the first element, last to get the last one or all to get all elements stored in an array called @wanted_ads.

@wanted_ads = WantedAd.where(:user_id => params[:id]).all

You can then go through this array and choose the attributes you want to pass to the view for each element.

Just a tip:

You should have in your User model an ActiveRecord relation, like this:

has_many :wanted_ads

And in your WantedAd model, like this:

belongs_to :user

And with this, you have a relation of one-to-may.

Then, you can do this:

def show
    @user = User.includes(:wanted_ads).find(params[:id])
end

And then, in your view:

<% @user.wanted_ads.each do |wanted_ad| %>
    <%# do something %>
<% end %>
Gustavo Semião-Lobo
  • 2,468
  • 3
  • 18
  • 26
0

where returns a collection of objects, not just a single object. So depending on what's returned you'll want to either call first to get the single instance that ought to return, or call each to iterate over the wanted ads and display them on your page.

You're seeing an instance of ActiveRecord::Relation in pry because of the underlying query mechanism that lazy loads the results. More details can be found here.

Community
  • 1
  • 1
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
0

Assuming your @wanted_ads is not nil and you want to loop through all the wanted ads...

<% @wanted_ads.each do |wanted_ad| %>

<%= wanted_ad.some_attribute_of_wanted_ad %>

<% end %>  

I would also suggest you be aware of SQL injection with the following code in your controller.

@wanted_ads = WantedAd.where(:user_id => params[:id])

As it should be

@wanted_ads = WantedAd.where(":user_id => ?", params[:id])
thank_you
  • 11,001
  • 19
  • 101
  • 185
  • No problem. Remember to check the answer that gave you the best help, whether it be mine or one of the other answers. – thank_you Apr 22 '13 at 15:17