简体   繁体   English

条件模型更新-Rails 3.1

[英]Conditional model updating — Rails 3.1

I have two tables: 我有两个表:

stores raw_stores_data 商店raw_stores_data

The raw_stores_data is received from a third party daily. 每天都会从第三方收到raw_stores_data。

I'd update certain fields of the stores model if those fields have been modified for that record in raw_stores_data. 如果已针对raw_stores_data中的记录修改了某些字段,我将更新商店模型的某些字段。

Currently I have a bunch of conditional statements that check each of those fields. 目前,我有一堆条件语句检查每个字段。 Is there any better way to code this? 有没有更好的方法编写此代码?

new_data = raw_stores_data.all.select do |item|
   item.store_id.present?
end

new_data.each do |item|
  if item.field1 != item.stores.field1
  ...
  ...
  ...

  # update record with hash of fields to update created above
end

You could add an association and special mutators to the 'raw' model that know how manipulate the 'stores' object. 您可以向“原始”模型添加一个关联和特殊的变体,以了解如何操纵“商店”对象。 This serves to keep the model code in the model. 这用于将模型代码保留在模型中。 Thin controller, comprehensive models, etc. 薄控制器,综合型号等

class Store < ActiveRecord::Base
  has_one :raw_stores_data
end


class RawStoresData < ActiveRecord::Base
  belongs_to :store

  def field1=(value)
    store.field1 = value
    store.save!
    field1 = value
  end
end

I'm hand waving at some of the details, and you might want to reverse the direction of the association or make it go both directions. 我在挥舞着一些细节,您可能想反转关联的方向或使其朝着两个方向发展。

EDIT: 编辑:

You would use this as such: 您可以这样使用:

raw_data = RawStoreData.find(param[:id]) # or new or however you get this object
raw_data.field1 = param[:field1]

The act of assigning will use the 'field1=' method, and make the change to the associated store object. 分配操作将使用“ field1 =”方法,并对关联的存储对象进行更改。 If you're worried about saving unnecessarily, you could conditionalize in that method to only save if the value changed. 如果您担心不必要的保存,则可以使用该方法作为条件,仅在值更改时保存。

I hope this is clearer. 我希望这更清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM