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