简体   繁体   中英

Mark as Sold Ruby rails

I am trying to implement a button 'Sold' for user if he/she sold the item. What I have in mind on trying to implement this is to add a new column to my product's table. And if it is sold, I will then need to update attribute of the data. If referring to this link, http://apidock.com/rails/ActiveRecord/Base/update_attributes

This is something that I should do? Am I right?

model/product

class Product < ActiveRecord::Base
  attr_accessible :sold
end

product controller

def sold
  @product = Product.find(params[:product_id])
  @product.sold = 'true'
  save
  redirect_to product_path
end

views/products/show

 <button type="button" class="btn btn-default"><%= link_to 'Sold', idontknowwhatotputhere %></button>

This also relate to what I am unsure with. What should I put at the link_to? and also how do I tell my application to relate to the def sold I have stated earlier?

Well, a couple things here.

  1. Don't do special actions in the controller unless you have a good reason to do so. All you are doing is updating a product. So name the route 'update'. And then in the link just do a put request with the sold=true. Keeps things RESTful and conventional.

  2. Once you do that, in your controller you will want to do validation and such.

     def update if product && product.update(product_params) redirect_to product_path else redirect_to edit_product_path end end private def product @product ||= Product.find(params[:id]) end def product_params params.require(:product).permit(:sold) end 

3.To add the link in your application to update it will be something like this.

<%= link_to 'Mark as sold', product_path(@product, product: {sold: true} ), method: :put %>

Your first need to declare the route, something like this in routes.rb :

resources :products do

  get :sold, on: :member

end

then that route should generate a path helper like 'sold_product' and you can use it like:

 <button type="button" class="btn btn-default"><%= link_to 'Sold', sold_product(@product.id) %></button>

you can check the helpers using 'rake routes'

about update the attribute, you can use:

 @product.update_attribute(:sold, true)

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