Ruby-on-rails Rails:如何在视图中确定控制器/动作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8053312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails: How to determine controller/action in view
提问by Rails beginner
This is my form partial:
这是我的表格部分:
<%= f.simple_fields_for :photo_attributes, :html => { :multipart => true } do |d| %>
<%= d.label :image, :label => 'Upload logo', :required => false %>
<%= d.file_field :image, :label => 'Image, :required => false', :style => 'margin-bottom:2px' %>
<%= d.input :image_url, :label => 'Billed URL', :required => false %>
<% end %>
If the action is edit I want to show this instead:
如果操作是编辑,我想改为显示:
<%= f.simple_fields_for :photo, :html => { :multipart => true } do |d| %>
<%= d.label :image, :label => 'Upload logo', :required => false %>
<%= d.file_field :image, :label => 'Image, :required => false', :style => 'margin-bottom:2px' %>
<%= d.input :image_url, :label => 'Billed URL', :required => false %>
<% end %>
How can i achieve this?
我怎样才能做到这一点?
采纳答案by tadman
Generally the form partial only contains the fields, not the form tag or the fields for, but if you have no other way, you can always see what params[:action]is currently set to and behave accordingly.
通常表单部分只包含字段,不包含表单标签或字段,但如果您没有其他方法,您总是可以看到params[:action]当前设置的内容并相应地进行操作。
回答by fny
current_page?(action: 'edit')
current_page?(action: 'edit')
See ActionView::Helpers::UrlHelper#current_page?
请参阅ActionView::Helpers::UrlHelper#current_page?
Rails also makes the methods controller_path, controller_name, action_nameavailable for use in the view.
轨道也使得方法controller_path,controller_name,action_name可以在视图中使用。
回答by nathanvda
You could write something like
你可以写类似的东西
<%- form_url = @object.new_record? ? :photo_attributes : :photo %>
<% f.simple_fields_for form_url, :html => { :multipart => true } do |d| %>
That is, if you have an @objectto check against. Otherwise you could use action_name(and even controller_name).
也就是说,如果你有一个@object检查。否则你可以使用action_name(甚至controller_name)。
So something like:
所以像:
<%- form_url = action_name == :edit ? :photo : :photo_attributes %>
<% f.simple_fields_for form_url, :html => { :multipart => true } do |d| %>
Hope this helps.
希望这可以帮助。
回答by thedanotto
Rails 5: Display Action within the view
Rails 5:在视图中显示操作
<%= action_name %>
If statement within the view
视图中的 if 语句
<% if action_name == "edit" %>
This is an edit action.
<% end %>
回答by Arugin
Just use @_controller.action_name in view
只需在视图中使用@_controller.action_name

