Guarana Fitgum
Guarana Fitgum

Reputation: 3

How to display all instances of a model in Rails?

In my web application the user can select certain instances of an entity. For instance on the class BubbleGum, now the user can select certain instances of BubbleGum by adressing their identifier:

gums/details?show=3532667

Now, in addition I also want to make it possible to display all BubbleGums. For this I have introduced the convention of using * to identify all

gums/details?show=*

This works nice so far, but often I have to add a bit code to process the * selection. Is there a nice way to represent an all-instances object in Ruby and/or Rails?

I have thought of using simply a dedicated symbol, constants, or an actual object of the class BubbleGum that represents all the other bubble gums.

Upvotes: 0

Views: 3654

Answers (2)

I think you want to use the query string param show. So, you can try in your gums controller:

def details
    if params[:show] == "*"
        @bubble_gums = BubbleGum.all 
        # ...
    elsif params[:show]
        @bubble_gum = BubbleGum.find(params[:show]) 
        # ...
    else 
        render :status => 404
    end
end

Upvotes: 1

Bot
Bot

Reputation: 1011

To display all the entities in a rails application generally we use a index page.

bubble_gums_controller.rb

def index
  @bubble_gums = BubbleGum.all
end

views/bubble_gums/index.html.erb

<% @bubble_gums.each do |bubble_gum| %>
  <tr>
    <td><%= bubble_gum.name %></td>
    <td><%= bubble_gum.price %></td>
  </tr>
<% end %>

Refer this for further details.

http://guides.rubyonrails.org/getting_started.html#listing-all-posts

Upvotes: 1

Related Questions