[英]ruby/rails - Converting Entire Database Field (from string to date)
[英]Ruby on Rails button to change the date field in the database to the current date for all products in the shopping list
一个用户可以有多个列表,一个列表可以有多个产品
产品具有名称和最后购买日期
我正在尝试为每个购物清单添加一个按钮,在单击该按钮时,应该将添加到清单中的所有特定产品的last_purchase日期更新为当前日期
这就是我现在所拥有的
index.html.erb(在列表视图文件夹中){每个列表都有此按钮}
<%= button_to "Just-Shopped", just_shopped_product_path(...), :method => :put %>
的routes.rb
resources :products do
member do
put 'just_shopped'
end
end
我知道我打算在列表的控制器中创建一个函数,但是我不确定如何从列表中选择所有产品而忽略未选择的产品,然后使用当前日期更新last_purchased字段
您处在正确的轨道上-首先,您似乎希望将按钮应用于列表的产品而不是单个产品,因此让我们将路线更改为:
resources :lists do
member do
put 'just_shopped'
end
end
end
然后在我们的lists_controller中:
class ListsController < ApplicationController
...
def just shopped
list = List.find(params[:id])
list.products.each do |product|
product.update_attributes(last_purchased: DateTime.now)
end
end
那是我们的路线和控制器动作设置,现在我们只需要添加正确的按钮即可。 我假设您有一个@lists变量(或current_user.lists之类的东西),并且您正在像这样遍历它们:
<% @lists.each do |list| %>
<%# whatever html you want for each list %>
<%= button_to "Just-Shopped", just_shopped_list_path(list), :method => :put %>
end
在控制器中更新产品后,还需要确定要重定向到的位置
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.