[英]How to display all instances of a model in Rails?
In my web application the user can select certain instances of an entity. 在我的Web应用程序中,用户可以选择实体的某些实例。 For instance on the class
BubbleGum
, now the user can select certain instances of BubbleGum
by adressing their identifier: 例如,在
BubbleGum
类BubbleGum
,现在用户可以通过使用其标识符来选择BubbleGum
的某些实例:
gums/details?show=3532667
Now, in addition I also want to make it possible to display all BubbleGums
. 现在,此外我还希望能够显示所有的
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? 有没有一种很好的方法来表示Ruby和/或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. 我曾想过使用一个专门的符号,常量或类
BubbleGum
的实际对象来代表所有其他泡泡糖。
To display all the entities in a rails application generally we use a index page. 要显示rails应用程序中的所有实体,我们通常使用索引页面。
bubble_gums_controller.rb bubble_gums_controller.rb
def index
@bubble_gums = BubbleGum.all
end
views/bubble_gums/index.html.erb 视图/ 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 http://guides.rubyonrails.org/getting_started.html#listing-all-posts
I think you want to use the query string param show. 我想你想使用查询字符串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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.