简体   繁体   中英

Rails 4 Form - Adding a new input to an existing record

I have a form where users enter profile info which is saved in the User model. I need to collect another piece of information from users at a later stage (on a different page). How do I collect this info and append it to the existing user record?

Here is my form code with the one additional input I need from the user. When I hit submit, it runs without error but the new field is not saved in my model. I ran the migration to add the field to the model.

<%= form_for @user, html: { method: :put }) do |f| %>

 <div class="form-group">
  <%= f.label :what_is_your_favorite_color %>
  <%= f.text_field :color, class:"form-control" %>
 </div>

 <div class="form-group">
    <%= f.submit "Submit", class:"btn btn-primary" %>
 </div>

<% end %>

My controller update method is currently blank .. can you tell me what the update method should look like? The user is logged in so I need to find that user record (probably by id column?) and write or update the new input into the model.

def update
   ??    
end

You first need to fetch your record, the pass it the params hash, and Rails will do the rest.

def update
  @record = Record.find(params[:id])
  if @record.update(record_params)
    redirect_to @record
  else
    render :edit
  end
end

If you are using Rails 4, you need to account for strong_parameters . So add the new attribute to the permitted attributes.

  def record_params
    params.require(:record).permit(:color, :and, :other, :attributes, :go, :here)
  end

The above code assumes that the record id will be in the params hash, or in other words, you are using RESTful routes. If you are not, you may want to pass in the id from the session (if this is, as you say, a user record, and you are using Devise).

def update
  @record = Record.find(current_user)
  # ... the rest should be the same
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM