ruby on rails在模型内部实例化



不知何故,我刚刚成为rails的中级(:D),我开始处理更复杂的项目,这些项目需要多个类和与我的模型的交互,我有点迷失在如何设计/排序我的代码上。

我有一个product_table和一个product_details_table。

每次创建产品时,都会上传一张图片。

在Product类中,我创建了一些方法来填充与该图像(大小等)相关的产品的虚拟属性。这一切都与回形针上传后的回调有关。

我的问题是,根据这个图像大小,我想在product_details表中自动生成属性值。

Product_details.new(product_id:current_product_id(**is it self.id here?**),size:product.virtual_attribut_size,x:virtual_attribut_x)

你会怎么做?

我会在我的控制器中完成,因为它必须在文件上传后自动完成,而不是之前,我不知道如何做到这一点。

如果我在我的模型中这样做,我猜它可以工作(作为一个普通类),但这就是方法吗?

感谢那些试图帮助的人

编辑:

基本上,我的产品型号如下:

class Product < ActiveRecord::Base
  def image_to_inch
    #return "30x30" (in inch) for an image uploaded in pixel (divide      the number of pixel by 300dpi to get a good quality print )
  end
  def image_printable_size
    #use previous method result to output an array of all printable size from a list of predifined sizes. example : 30x30 can be printed in 30x30,20x20,10x10 but not 40x40.
    #output ["30x30","20x20","10x10"]
  end
##Here i should iterate over the array and create a product_details line for that product for each size :
   ## simplified version of what i was going for and that look really really ugly :
  ["30x30","20x20","10x10"].each do |size|
    ProductDetail.create!(product_id:self.id,size:size)
  end
end

我省略了回调、验证等。这样更容易阅读。

您的需求并不明确,但这里有一些策略提示。

  1. 使用before_save或after_save回调可以自动执行代码
  2. 使用attr_accessor变量保存before_save和after_save回调使用的临时对象
  3. 用简单的方法做简单的事情。请记住,您可以编写自己的自定义getter和setter方法

所以,你的方法可能是这样的:我在猜测你的模式,所以不要太在意细节。

class Product
  has_one :product_detail
  after_save :update_product_details
  def update_product_detail
    product_detail = self.product_detail || self.product_detail.build
    if self.image
      product_detail.update_from_image(self.image)
    end
    product.save
  end
class ProductDetail
  belongs_to :product
  def update_from_image(image)
    self.size = image.size
    #... any other settings taken from the image
  end

最新更新