0

我有两个模型,产品和订单。

Product
 - cost
 - id

Order
 - cost
 - product_id

每次有人下订单时,它都会通过“新订单”表单中的单选按钮值捕获 product_id。

在控制器中创建新订单时,需要将 order.cost 设置为 order.product.cost。从逻辑上讲,我认为代码应该是这样的:

def create
...
   @order.cost == @order.product.cost
...
end

但是我似乎根本无法让它工作,因此我在这里问这个问题。

任何帮助回答(或命名)问题将不胜感激。

4

2 回答 2

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

假设您在模型中正确编写关联,它应该如下所示

产品.rb

has_many :orders

订单.rb

belongs_to :product
于 2010-04-12T03:36:32.863 回答
0

另一种选择是在 Order 模型上指定 before_create ,但这仅在需要以这种方式创建每个 Order 时才有效。

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
于 2010-04-12T04:20:18.607 回答