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 avoid 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 に答える