Blankman
Blankman

Reputation: 266910

How can a single form_for work for new, update and edit?

In rails 3, is it possible to create a form_for that works for both new, update and edit actions?

If yes, how do I do this?

I have a admin section so my urls look like:

/admin/posts/ {new,update, edit}

Upvotes: 15

Views: 13237

Answers (2)

Rabbott
Rabbott

Reputation: 4332

Because new needs to be sent to create, and edit needs to be sent to update a single form_for will not work.. unless (which I don't necessarily recommend) you place a tertiary operator in the form_form params

form_for(@post, :url => (@post.new_record? ? admin_posts_url : admin_post_url(@post)))

Because in your new action you are going to have Post.new which creates an object with a nil id, and in your edit action you will have Post.find(params[:id])

Upvotes: 22

james
james

Reputation: 452

Just let form_for handle it:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style

controller:

class ControllerName
  def new
    @post = Post.new
  end
  def edit
    @post = Post.find params[:id]
  end
end

view:

<%= form_for [:admin, @post] do |f| %>
<% end %>

Upvotes: 30

Related Questions