Christian
Christian

Reputation: 391

Rails Forms - Edit User Form

I am trying to create an Edit User Form to amend the user details stored in my database but keep getting error. I have changed the form URL and tried changing it to a method: :get without much success.

Edit User Form

<%= form_with url: @user, :class => "user_sign_in_form" do |form| %>
  <%= form.text_field "user[email]", placeholder: "email", :class => "form_box" %>
  <%= form.text_field "user[username]", placeholder: "username", :class => "form_box"%>
  <%= form.text_field "user[password]", placeholder: "password", :class => "form_box" %>
  <%= form.submit "SUBMIT" %>
<% end %>

Edit Action

  def edit
    @user = User.find(params[:id])
  end

Link to Edit User Form

 <%= link_to "Edit", edit_user_path(@user) %>

Error Message

No route matches [POST] "/users/58"

Upvotes: 0

Views: 530

Answers (1)

max
max

Reputation: 101811

You need to use model: @user not url: @user.

<%= form_with model: @user, :class => "user_sign_in_form" do |form| %>
  <%= form.text_field :email, placeholder: "email", :class => "form_box" %>
  <%= form.text_field :username, placeholder: "username", :class => "form_box"%>
  <%= form.password_field :password, placeholder: "password", :class => "form_box" %>
  <%= form.submit "SUBMIT" %>
<% end %>

When you pass a model form_with will set both the action (/users or /users/:id) and method (POST or PATCH) depending on if the record has been saved. See Resource Routing: the Rails Default.

The url: option should really only be used if you have to override the conventional routes or if you have a form that does not wrap a model instance.

Also use form.text_field :email instead which will "bind" the input to the model attribute. Nobody likes having to refill an entire form from scratch because they missed some minor detail.

And on a side note do not use placeholders instead of labels - its an aweful practice from both a useability and accessibility standpoint.

Upvotes: 3

Related Questions