Zachary Weixelbaum Zachary Weixelbaum - 6 months ago 11
Ruby Question

Create link in Ruby on Rails to update a specific database entry

I am new to Ruby on Rails and I want to create a very simple application. I used scaffolding to create a database called users. Two of the fields in users are

limit
and
containers
, which is the max number of containers a user can have and the remaining total containers that they can have. They both start off at a given number (e.g. 15), but when a user takes one
containers
will go down to 14 and will continue to decrease every time they take one, until it reaches 0. When a user returns a container, the number for
container
goes up by one until the max number, 15 in my example.

Since I created this using Ruby scaffolding, I can just go to the edit page for each user right now and manually change the
containers
value, but that can allow me to change it to any number. On the
users/:id
page I want to have a link like the edit link that is there right now

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


and have something similar, but along the lines of

<%= link_to 'Take container', #run method to decrease and return here# %>
<%= link_to 'Return container', #run method to increase and return here# %>


For now, all I care about is just changing the number and elsewhere I will be rendering the user information.

Answer

AJAX would be a good fit here, but that would complicate the question, so I will stick to doing it with Rails.

You will first need to edit your routes.rb file to include something like:

get '/remove_container/:user_id', to: 'users#remove_container', :as => :remove_container
get '/add_container/:user_id', to: 'users#add_container', :as => :add_container

Then add methods in your Users controller:

def remove_container
  user_id = params[:user_id]
  @user = User.find user_id
  # code to change container number
  redirect_to edit_user_path(@user)
end
def add_container
  user_id = params[:user_id]
  @user = User.find user_id
  # code to change container number
  redirect_to edit_user_path(@user)
end

There are a lot of things to make this better, but this should get you going in the right direction anyway.

Links to these could be made manually or done with paths:

<a href="/remove_container/[:user_id]">Remove Container</a>

or

link_to "Remove Container", remove_container_path(@user)
Comments