Update a record with a button in Rails?

ruby-on-rails, ruby-on-rails-3

Solution

You need a form for that instead of just abutton

<%= form_tag add_school_user_path(@user), method: put do -%>
  <%= hidden_field_tag :school_id, @school.id -%>
  <%= submit_tag 'Add school' -%>
<%- end -%>

you didn't provide the context code, maybe @user and @school are not the real variable names but you can get the idea from this

Problem

I'm trying to update a record in my Rails app using a button. I have a User and I want to update its school_id value. I have a School view page where a User can click on a button to add that school's id to the User school_id field. I'm struggling with the implementation. Here's what I have so far: User controller: ``` def add_school @user = User.find(params[:user_id]) @user.update_attributes(:school_id) respond_to do |format| flash[:notice] = "School has been added!" format.html { redirect_to :back } format.js end ``` Button on School show page: ``` <%= button_to "Add School", add_school_user_path, :method => "put" %> ``` I tried to do this a different way by just adding code to the update action in the User controller but I couldn't get that to work either: ``` def update @user = User.find(params[:id]) if @user.update_attributes(params[:school_id]) flash[:notice] = "School has been added!" redirect_to @user end if @user.update_attributes(params[:user]) flash[:notice] = "Successfully updated account and profile!" end end ``` What's the best way to pass the School's id into the User school_id column? Thanks!! EDIT 1: Routes ``` resources :users do member do get :following, :followers put :add_school end ``` Updated controller: ``` def add_school @user = current_user @school = School.find(params[:id]) @user.update_attributes(school_id: params[:school_id]) respond_to do |format| flash[:notice] = "School has been added!" redirect_to @user.school end end ``` Updated button link: ``` <%= button_to "Add School", add_school_user_path(@user, school_id: @school.id), :method => :put %> ``` Routing error: ``` No route matches {:action=>"add_school", :controller=>"users", :school_id=>1, :id=>nil} ```

Original source