0

鉴于我有以下模型:

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)

谢谢!

4

2 回答 2

1

T避免 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) )
于 2013-03-29T16:57:43.503 回答
0

我不知道为什么我没有马上想到这个。我想也许是通过我的联想。不过这很容易。

要清理,create我只需要在上创建一个虚拟属性Rule

def phrase=(phrase)
  self.verb = phrase.verb
  self.noun = phrase.noun
end

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

要清理 arelwhere查询,我只需要在规则上创建一个范围。

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

# which allows me to
Rule.with_phrase(phrase)
于 2013-03-29T17:08:07.437 回答