简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM