使用嵌套资源的控制器中的设置值
问题描述:
我有两个模型,产品和订单。使用嵌套资源的控制器中的设置值
Product
- cost
- id
Order
- cost
- product_id
每次有人下订单,它通过在“新秩序”形式的单选按钮值捕捉PRODUCT_ID。
在控制器创建新订单时,需要将order.cost设置为order.product.cost。按道理我认为代码应该是这样的:
def create
...
@order.cost == @order.product.cost
...
end
但是我似乎无法使它在所有的工作,因此我问这个问题在这里。
任何帮助回答(或命名)的问题将不胜感激。
答
语法错误
@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
或der.rb
belongs_to :product
答
另一个选择是指定的订单模型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