我有两个型号,产品和订单。
Product
- cost
- id
Order
- cost
- product_id
每当有人下订单时,它会通过“新订单”表单中的单选按钮值捕获product_id。
在创建新订单时的控制器中,需要将order.cost设置为order.product.cost。从逻辑上讲,我认为代码应该是这样的:
def create
...
@order.cost == @order.product.cost
...
end
然而,我似乎无法使其发挥作用,因此我在这里提出问题。
任何帮助回答(或命名)的问题将不胜感激。
答案 0 :(得分:0)
语法错误
@order.cost == @order.product.cost #it will compare the product cost & order cost & return boolean value true ot false
它应该是
@order.cost = @order.product.cost
假设你在模型中正确地写了关联,它应该如下
product.rb
has_many :orders
order.rb
belongs_to :product
答案 1 :(得分:0)
另一种选择是在Order模型上指定before_create,但这只有在需要以这种方式创建每个订单时才有效。
class Order < ActiveRecord::Base
has_many :products
#this could be has_one if you really want only one product per order
accepts_nested_attributes_for :products
#so that you can do Order.new(params[:order])
#where params[:order] => [{:attributes_for_product => {:id => ...}}]
#which is handled by fields_for in the view layer.
#has_one would make this :product
before_create :calculate_order_cost_from_product
#only run on the first #save call or on #create
def calculate_order_cost_from_product
self.cost = self.products.first.cost
#this could also be self.products.sum(&:cost)
#if you wanted the total cost of all the products
#has_one would be as you had it before:
#self.cost = self.product.cost
end
end