标记为已售出 Ruby rails
Mark as Sold Ruby rails
如果 he/she 售出商品,我正在尝试为用户实现一个按钮 'Sold'。在尝试实现此功能时,我想到的是在我的产品 table 中添加一个新列。如果它被出售,我将需要更新数据的属性。如果参考这个link,http://apidock.com/rails/ActiveRecord/Base/update_attributes
这是我应该做的事情?我说的对吗?
model/product
class Product < ActiveRecord::Base
attr_accessible :sold
end
产品负责人
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>
这也涉及到我不确定的地方。我应该在 link_to 放什么?以及我如何告诉我的应用程序与我之前声明的 def sold 相关?
你首先需要声明路线,在routes.rb中是这样的:
resources :products do
get :sold, on: :member
end
那么该路由应该生成一个像 'sold_product' 这样的路径助手,你可以像这样使用它:
<button type="button" class="btn btn-default"><%= link_to 'Sold', sold_product(@product.id) %></button>
您可以使用 'rake routes'
检查助手
关于更新属性,您可以使用:
@product.update_attribute(:sold, true)
嗯,这里有几件事。
除非有充分的理由,否则不要在控制器中执行特殊操作。您所做的只是更新产品。所以将路线命名为'update'。然后在 link 中使用 sold=true 执行一个 put 请求。保持事物 RESTful 和传统。
完成后,您将需要在控制器中进行验证等。
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 在你的应用程序中添加 link 来更新它会是这样的。
<%= link_to 'Mark as sold', product_path(@product, product: {sold: true} ), method: :put %>
如果 he/she 售出商品,我正在尝试为用户实现一个按钮 'Sold'。在尝试实现此功能时,我想到的是在我的产品 table 中添加一个新列。如果它被出售,我将需要更新数据的属性。如果参考这个link,http://apidock.com/rails/ActiveRecord/Base/update_attributes
这是我应该做的事情?我说的对吗?
model/product
class Product < ActiveRecord::Base
attr_accessible :sold
end
产品负责人
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>
这也涉及到我不确定的地方。我应该在 link_to 放什么?以及我如何告诉我的应用程序与我之前声明的 def sold 相关?
你首先需要声明路线,在routes.rb中是这样的:
resources :products do
get :sold, on: :member
end
那么该路由应该生成一个像 'sold_product' 这样的路径助手,你可以像这样使用它:
<button type="button" class="btn btn-default"><%= link_to 'Sold', sold_product(@product.id) %></button>
您可以使用 'rake routes'
检查助手关于更新属性,您可以使用:
@product.update_attribute(:sold, true)
嗯,这里有几件事。
除非有充分的理由,否则不要在控制器中执行特殊操作。您所做的只是更新产品。所以将路线命名为'update'。然后在 link 中使用 sold=true 执行一个 put 请求。保持事物 RESTful 和传统。
完成后,您将需要在控制器中进行验证等。
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 在你的应用程序中添加 link 来更新它会是这样的。
<%= link_to 'Mark as sold', product_path(@product, product: {sold: true} ), method: :put %>