Ronye Lago Ronye Lago - 5 months ago 13
Ruby Question

function to change attribute using a button

I am creating a small college project in Ruby on Rails, and I came across a problem: I have a table named Person and another called Tools.
People have many tools and each tool and possessed by a person.
I need to add a feature that allows the loan of tools between people of the system. For this, I created an attribute called 'loan' in the Tools table, which has a value of 0 means that the tool not this borrowed and if it is 1, that this borrowed. In view show the tools, I created a button with the function to borrow the tool. My problem is how do to make this button change the attribute 'loan' from the Tools table from 0 to 1 and then reverse it. Someone would have a solution or a better suggestion?

Answer

I would create 2 routes name "barrow" and "retrieve" like this:

  #config/routes.rb
  get '/tool/:id/barrow' => 'tools#barrow', as: :barrow
  get '/tool/:id/retrieve' => 'tools#retrieve', as: :retrieve

Now in your view you can do something like

# tool.index.html.erb
...
<% if tool.loan %>
  <%= link_to retrieve_path(tool), 'Retrieve', class: 'btn ...' %>
<% else %>
  <%= link_to barrow_path(tool), 'Barrow', class: 'btn ...' %>
<% end %>
...

now you have to create the controller action you have to create the retrieve and barrow methods

#app/controllers/tool_controller.rb
class UserController < ApplicationController
  ...
  def retrieve
    @tool = Tool.find_by(params[:tool])
    @tool.update_attributes(:loan, 0)
  end

  def barrow
    @tool = Tool.find_by(params[:tool])
    @tool.update_attributes(:loan, 1)
  end
  ...
end

I hope that this help you

Comments