清除活动记录中属性组的api?

时间:2013-03-29 16:16:40

标签: ruby-on-rails activerecord struct

鉴于我有以下型号:

class Rule < ActiveRecord::Base
  belongs_to :verb
  belongs_to :noun
  ...
end

class Verb < ActiveRecord::Base; end
  has_many :rules
end

class Noun< ActiveRecord::Base; end
  has_many :rules
end

而且,因为我使用动词+名词作为一对,我有以下帮助(不可持久):

class Phrase < Struct.new(:verb, :noun); ...; end

我该怎么做呢:

phrase = Phrase.new(my_verb, my_noun)

# sadface
Rule.create(verb: phrase.verb, noun: phrase.noun)
Rule.where(verb_id: phrase.verb.id).where(noun_id: phrase.noun.id)

# into this?
Rule.create(phrase: phrase)
Rule.where(phrase: phrase)

谢谢!

2 个答案:

答案 0 :(得分:1)

避免使用Rule.where(...)。where(...)你可以创建一个范围:

class Rule < ActiveRecord::Base
  scope :with_phrase, lambda { |p| where(verb: p.verb, noun: p.noun) }
end

然后:

Rule.with_phrase( Phrase.new(my_verb, my_noun) )

答案 1 :(得分:0)

我不知道为什么我没有立刻想到这一点。我想也许通过我关联。这很容易。

要清理create,我只需要在Rule

上创建一个虚拟属性
def phrase=(phrase)
  self.verb = phrase.verb
  self.noun = phrase.noun
end

# which allows me to
Rule.create(phrase: my_phrase)

要清理arel where查询,我只需要在规则上创建范围。

def self.with_phrase(phrase)
  where(verb: p.verb, noun: p.noun)
end

# which allows me to
Rule.with_phrase(phrase)