Rails: Conditional path in form partial

霸气de小男生 提交于 2019-12-05 21:07:32
pauloancheta

You can post local variables into the partial. Something like the following would work:

new.html.erb

<%= render partial: '_form', locals: {url: user_wikis_path, method: :post} %>

edit.html.erb

<%= render partial: '_form', locals: {url: user_wiki_path(@user, @wiki), method: :post} %>

_form.html.erb

<%= simple_form_for [@user, @wiki], url: url, method: method do |f| %>
  <%= f.input :title %>
  <%= f.input :body %>
  <%= f.submit class: "btn btn-success"  %>
<% end %>

Or you could set @url and @method as instance variables and access them that way.

Controller

def new
  @method = :get
  @url = user_wikis_path
  ...
end

def edit
  @method = :post
  @url = user_wiki_path(@user, @wiki)    
  ...
end

_form.html.erb

<%= simple_form_for [@user, @wiki], url: url, method: method do |f| %>
  ...

Or you could have a conditional in the form that accesses the current action, if you use action_name in the view it'll return the name of the current action.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!