dodgerogers747
dodgerogers747

Reputation: 3345

Fetch name of ActiveRecord::Relation object

Afternoon all,

I have a Month model which has many hotels. A hotel belongs_to a month and has a name, info, picture, twitter_id etc and a winner column, which is a boolean. In my index view for months, for each month i would like to show the name of the hotel where "winner" is true.

I have been trying the following where queries;

<% @months.each do |month| %>
    <td><%= month.date %></td>
    <td><%= month.created_at.strftime("%v") %></td>
    <td><%= month.hotels.where(winner: "true") %></td>
<% end %>

and this returns; #<ActiveRecord::Relation:0x007fae1ed9cd70> (slapping .name on the end just gives the relation name of "hotel")

How could I perform a query that retrieves the winning hotel's name?

Any pointers would be great thanks, my code is as follows;

months_controller.rb

def show
    @month = Month.find(params[:id])
    @hotels = @month.hotels
  end

  def index
    @months = Month.paginate(page: params[:page], per_page: 10).includes(:hotels)
  end

If you need more code just shout. cheers Andy

Upvotes: 0

Views: 68

Answers (2)

MurifoX
MurifoX

Reputation: 15089

When you do a where query, it returns to you an array of the hotels object. Maybe you should try to use a find_by alternative to retrieve only one hotel like this:

month.hotels.find_by_winner(true).name

EDIT:

<% winner = month.hotels.find_by_winner(true) %>
<%= winner.name if winner %>

This way the name method would be called only if winner is not nil.

Upvotes: 1

Erez Rabih
Erez Rabih

Reputation: 15788

Assuming there is one winner in each month:

month.hotels.where(winner: "true").first.try(:name)

If there may be many winners you can do:

month.hotels.where(winner: "true").pluck(:name)

This will return an array of all winners names.

Upvotes: 1

Related Questions