在我的标题中,用户可以通过表单添加“项目”。我希望每个页面都有这个选项,所以我的标题中有:
<%= form_for(@item) do |f| %>
<div>
<div class="title"><%= f.label :name, "Name" %></div>
<div class="champ"><%= f.text_field :name %></div>
</div>
<div>
<%= f.submit "add this item" %>
</div>
<% end %>
但它迫使我在每个控制器中添加它:
def action
@item = Item.new
end
我该如何避免它?使用应用程序控制器?
谢谢!
答案 0 :(得分:1)
在应用程序控制器中定义方法并使用before_filter
。
class ApplicationController < ActionController::Base
..
before_filter :initialize_item
def initialize_item
@item = Item.new
end
end
现在将对每个请求执行initialize_item方法。
答案 1 :(得分:1)
你可以这样做:
<%= form_for(Item.new) ...
但是如果该项目无效,则表单将为空(因为您为表单创建了一个新项目,而不是使用预填充值并由控制器验证的项目)。你可以尝试:
<%= form_for(@item || Item.new)...