[英]Ruby on Rails save a record on database based on post data
I've been playing around with this for the past 6 hours and I really can't solve it. 在过去的6个小时里,我一直在玩这个游戏,但我真的无法解决。 I'm new to ruby on rails.
我是红宝石的新手。 I have a products and I have added a purchases model.
我有一个产品,并且添加了购买模型。 now I want a 'buy' key next to each product to add it to my purchases database.
现在,我希望每个产品旁边都有一个“购买”键,以将其添加到我的购买数据库中。 This is my Purchases controller:
这是我的Purchases控制器:
class PurchasesController < ApplicationController
def new
end
def update
end
def create
@purchase = Purchase.new(purchase_params)
if Purchase.save
redirect_to products_path notice: 'Product bough'
else
redirect_to products_path notice: 'Error!!!'
end
end
private
def purchase_params
params.require(:product).permit(:amount,:product_id)
end
And the buy button: 和购买按钮:
<td><%= link_to 'Buy',purchases_path(product.attributes), method: :post %></td>
And that's within <% @products.each do |product %>
. 并且在
<% @products.each do |product %>
。 Now I really wanna know how to send product_id and then save it in my purchases database. 现在,我真的想知道如何发送product_id,然后将其保存在我的购买数据库中。 I keep getting all sorts of errors!
我不断收到各种各样的错误! Like
parameter not found: product
to undefined method
permit' for "8":String 8 is the product id and
method save is undefined ...`. 类似于
parameter not found: product
“ 8”的parameter not found: product
到undefined method
允许“:字符串8 is the product id and
方法的保存未定义...。 I think I really don't know what I'm doing here! 我想我真的不知道我在这里做什么! A little help or tutorial on how to manually save data to database will be appreciated.
对于如何将数据手动保存到数据库的一些帮助或教程将不胜感激。 (by manually I mean entering which posted field to saved for which col)
(我的意思是手动输入要为哪个列保存的已发布字段)
您应该执行@purchase.save
,而不是Purchase.save
Something like this should be your view. 这样的事情应该是您的看法。
<% @products.each do |product| %>
<td><%= product.amount %><td>
<td><%= form_for @product, url: {action: "create"}, html: {method: "post"} do |f| %>
<%= f.hidden_field_tag :id,product.id%>
<%= f.hidden_field_tag :amount,product.amount%>
<%= f.submit "Create" %>
<% end %></td>
<% end %>
Your controller should look something like this: 您的控制器应如下所示:
def create
@purchase = Purchase.new(purchase_params)
if @purchase.save
redirect_to products_path notice: 'Product bough'
else
redirect_to products_path notice: 'Error!!!'
end
end
def purchase_params
params.require(:product).permit(:amount,:id)
end
I am not sure why you want to not use the form. 我不确定您为什么不想使用该表格。 Why is that?
这是为什么? Anyway here is a solution.
无论如何,这是一个解决方案。
<td><%= link_to 'Buy',purchases_path(amount: product.amount,id: product.id), method: :post %></td>
This should work. 这应该工作。 Try this.
尝试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.