I'm trying to pass a url
and variable
to a form partial in Rails.
Method #1:
This works, but I'd rather not hardcode post_create_path
into the form, so that it can be used for #update as well.
new.html.erb
<%= render partial: 'shared/form', locals: { form: @form } %>
_form.html.erb
<%= form_for form, url: post_create_path do |f| %>
...
<% end %>
Method #2:
This does not work.
new.html.erb
<%= render partial: 'shared/form', locals: { form: @form, url: post_create_path } %>
_form.html.erb
<%= form_for form, url: url do |f| %>
...
<% end %>
Error:
undefined local variable or method `url' for #<#:0x007f8d4d831fd0>
What I've also tried:
url
instead of url:url
but getting the same error.I've been trying to make this work for a couple hours now and feel like I'm running out of options to try. Any help in pointing out what I'm doing wrong would be super appreciated!
you can use different actions by opening form_for
on edit and new view templates and then pass the form object to the partial which contains all the fields of the form that are common to both create and update
new.html.erb
<%= form_for @post, :url => { :action => "create" } do |form| %>
<%= render partial: 'shared/form', locals: { f: form } %>
edit.html.erb
<%= form_for @post, :url => { :action => "update" } do |form| %>
<%= render partial: 'shared/form', locals: { f: form } %>
shared/_form.html.erb
<%= f.text_field :title %>
...
<%= f.submit "Save" %>
<% end %>
Use the locals
hash as a form_for
argument:
# new.html.erb
<%= render partial: 'shared/form', form: @form, locals: { url: post_create_path, method: :post} %>
# edit.html.erb
<%= render partial: 'shared/form', form: @form, locals: { url: post_update_path, method: :put} %>
# _form.html.erb
<%= form_for form, locals do |f| %>
...
<% end %>
locals
is just a hash and you can give it any name (like vars
). Then use it consistently in the views and the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With