Ronye Lago Ronye Lago - 2 years ago 70
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 Source

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

  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 %>
  <%= 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

class UserController < ApplicationController
  def retrieve
    @tool = Tool.find_by(params[:tool])
    @tool.update_attributes(:loan, 0)

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

I hope that this help you

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download