Rails: Pass parameters with render :action?

前端 未结 4 1584
时光取名叫无心
时光取名叫无心 2020-12-08 07:14

I have a form that displays differently depending on the parameter it was called with.

Ex.

testsite.local/users/new?type=client

So

相关标签:
4条回答
  • 2020-12-08 07:46

    There are two ways to do it.

    Either add a hidden field or an extra parameter to the form_for

    Adding hidden field in your form containing named type and set it equal to params[:type] this will preserve the type on the render if validation fails.

    View code:

    <% form_for @user do |f| %>
    ...
    <%= hidden_field_tag :type, params[:type] %>
    <%end%>
    

    Adding an extra paramater to the form:

    <% form_for @user, create_user_path(@user, :type => params[:type]) %>
    ...
    <%end%>
    

    Either one will do what you want it to.

    0 讨论(0)
  • 2020-12-08 07:51

    Extract for Rails Guides

    Using render with :action is a frequent source of confusion for Rails newcomers. The specified action is used to determine which view to render, but Rails does not run any of the code for that action in the controller

    I believe your new?type=client is used to setup some kind of variable in your new action? And the variable is later used in your new.html.erb view?

    Then you need to change a little bit your create action like this:

      else
         # add code here to setup any variable for type = client
         # and which will be used in your view
         render :action => 'new'
      end
     end
    
    0 讨论(0)
  • 2020-12-08 07:54

    You could always force it by:

    params[:type] ||= "client"
    

    in your new action in your controller. If type is not set then it will default to client. The URL will not show this however.

    0 讨论(0)
  • 2020-12-08 07:59

    As elucidated by another user answering my other related question, here's what I was after:

    form_for @user, :url => { :action => :create, :type => @type }
    

    ... which preserves the parameter :type through each new render action (assuming I have it defined correctly in my controller).

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