Rails: How to determine controller/action in view

前端 未结 5 1560
半阙折子戏
半阙折子戏 2021-01-31 17:10

This is my form partial:

<%= f.simple_fields_for :photo_attributes, :html => { :multipart => true } do |d| %>
    <%= d.label :image, :label =>         


        
相关标签:
5条回答
  • 2021-01-31 17:40

    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 @object to check against. Otherwise you could use action_name (and even 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.

    0 讨论(0)
  • 2021-01-31 17:41

    Rails 5: Display Action within the view

    <%= action_name %>
    

    If statement within the view

    <% if action_name == "edit" %>
      This is an edit action.
    <% end %>
    
    0 讨论(0)
  • 2021-01-31 17:41

    Just use @_controller.action_name in view

    0 讨论(0)
  • 2021-01-31 17:42

    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.

    0 讨论(0)
  • 2021-01-31 17:46

    current_page?(action: 'edit')

    See ActionView::Helpers::UrlHelper#current_page?

    Rails also makes the methods controller_path, controller_name, action_name available for use in the view.

    0 讨论(0)
提交回复
热议问题