[英]Ruby on Rails: Including actions of different controllers into index view of another controller
I am currently into learning Ruby on Rails and I am stuck with a pretty simple thing. 我目前正在学习Ruby on Rails,并且坚持做一个非常简单的事情。 I already tried to google it (or look it up here), but I could not find the right answer (due to my RoR-beginnings it might searched with the wrong terms). 我已经尝试过搜索它(或在这里查找它),但是我找不到正确的答案(由于我的RoR开头,它可能搜索了错误的字词)。
I am working on a small learning project to list different items (items_controller). 我正在做一个小型学习项目,列出不同的项目(items_controller)。 Each of these items belong to a category. 这些项目均属于一个类别。 But because I want the users to either create, update or delete a category I created a categories_controller. 但是因为我希望用户创建,更新或删除类别,所以创建了Categories_controller。 Both controllers and views are working fine, but I want to include the Category of each item on the index-view (which is also the root_path) of my Items Controller. 控制器和视图都可以正常工作,但是我想将每个项目的类别包括在我的Items Controller的索引视图(也是root_path)上。 Here I get stuck (with the code and the logic behind it as well). 在这里,我陷入了困境(代码及其背后的逻辑也是如此)。 What is the best way to do this? 做这个的最好方式是什么?
Somehow I managed to get the category name into the edit.html.erb-form of the items_controller, but I don't really understand how: 我以某种方式设法将类别名称输入到items_controller的edit.html.erb-form中,但是我真的不太了解如何:
items_controller: items_controller:
def edit
@item = Item.find(params[:id])
@categories = Category.all.map{ |c| [c.name, c.id] }
end
edit.html.erb (this is actually in _form.html.erb and rendered in edit.html.erb): edit.html.erb(实际上在_form.html.erb中,并在edit.html.erb中呈现):
<%= simple_form_for @item, :html => { :multipart => true } do |f| %>
<%= f.select :category, @categories %>
<%= f.input :title %>
<%= f.input :url %>
<%= f.button :submit %>
<% end %>
If you want to include the category of each items, You need to specify which column of categories table you want to display. 如果要包括每个项目的类别,则需要指定要显示的类别表的哪一列。 Example : a column called name
: 示例:一个名为name
的列:
<% @items.each do |item| %>
<%= item.category.name %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.