在new.html.erb中,我有以下表格:
<div align="center">
<h1>What are your important <%= @category.bizdev %> Action items?</h1>
<%= form_for @category do |f| %>
<p>
<p>Store Answer Below:</p>
<%= f.text_field :name, :size => 40, :style => 'height: 40px' %>
</p>
<p>
<%=f.submit 'Save action item' %>
</p>
<% end %> </div>
第二行的@ category.bizdev从模型类别调用方法bizdev:
def bizdev
"Business Development"
end
但是 - 我有一个索引页面:
<h1>Select A Business Category To Begin Identifying Action Items</h1>
<ol><li><%= link_to 'Business Admin', 'new' %></li><br><br>
<li><%= link_to 'Business Development/Marketing', 'new' %></li><br><br>
<li><%= link_to 'Financial', 'new' %></li>
</ol>
<%= link_to 'Store random action items', new_facilitate_path %><br><br>
<%= link_to 'See a list of already stored action items', facilitates_path %>
链接到相同的新视图,具有不同的类别名称(业务开发,业务部门,业务财务)。我需要视图根据单击要发送到新表单的URL呈现相应的NAME或业务类别。
如果我不清楚,请告诉我。如果您需要更多我的代码,请告诉我。
谢谢!
答案 0 :(得分:0)
我希望我理解正确,我认为你应该
例如代码可能是这样的(注意link_to
中的路线助手)
#index page
# pay attention on routes!
<ol>
<li><%= link_to 'Business Admin', new_category_path(category_name: 'Business Admin') %></li><br><br>
<li><%= link_to 'Business Development/Marketing', new_category_path(category_name: 'Business Development/Marketing') %></li><br><br>
<li><%= link_to 'Financial', new_category_path(category_name: 'Financial') %></li>
</ol>
# new page
<h1>What are your important <%= bizdev %> Action items?</h1>
# helper
def bizdev
if ['Business Admin', 'Business Development/Marketing', 'Financial'].include?(params[:category_name])
params[:category_name]
else
@category.bizdev
end
end
一些解释:
include?
这只是一种保护,params category_name
属于允许的值(如果无效值以params为单位,则使用默认值)
category_name
进入url params。您应该了解用户可以传递任何我更喜欢的值来检查参数值。
“Rails如何将category_name与索引视图上的相应category_name对应?” - 您使用正确的link_to
构建category_name
作为参数(请参阅索引页示例)
以上示例仅适用于您的情况。也许你应该稍微改变架构。例如,将gem enumerize
应用于类别属性name
。然后在控制器操作new
中使用传递的参数category_name
构建新对象。
代码示例
# model
enumerize :name, in: [:business_admin, :business_development, :financial], default: :financial # need to update locale file
#controller
def new
@category = Category.new
@category.name = params[:name] # rename params to `name`
end
# new page
<h1>What are your important <%= @category.name_text %> Action items?</h1>