Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails从多个到多个模型_Ruby On Rails_Database_Relational Database_Has Many - Fatal编程技术网

Ruby on rails Rails从多个到多个模型

Ruby on rails Rails从多个到多个模型,ruby-on-rails,database,relational-database,has-many,Ruby On Rails,Database,Relational Database,Has Many,模拟以下情况的最佳方法是什么: Word belongs_to :wordable, :polymorphic => true Phrase has_many :words, :as => :workable belongs_to :story Line has_many :words, :as => :wordable belongs_to :story Story has_many :lines has_many :ph

模拟以下情况的最佳方法是什么:

Word
  belongs_to :wordable, :polymorphic => true


Phrase
  has_many :words, :as => :workable
  belongs_to :story

Line
  has_many :words, :as => :wordable    
  belongs_to :story


Story
 has_many :lines      
 has_many :phrases
 has_many :words, :through => :phrases
 has_many :words, :through => :lines
我希望能够做到

 @story.words 
要获取通过线条或短语链接到故事的所有单词的列表


这可能吗?

您可以从
故事
类中删除2个
has\u many:words,:to=>XXX
关系,并定义一个方法
words

def words 
  ([] << lines.collect {|line| line.words} << phrases.collect {|phrase| phrase.words}).flatten
end
def单词
([]试试这个:

class Story

  has_many :lines      
  has_many :phrases

  def words(reload=false)
    @words = nil if reload
    @words ||= Word.where("(wordable_type = ? AND wordable_id IN (?)) OR
                            (wordable_type = ? AND wordable_id IN (?))", 
                           "Phrase", phrase_ids, "Line", line_ids)    
  end
end
现在


谢谢,在Word模型中通过短语id和行id将多态性转换为关系是个坏主意?使用多态性关系,您将能够更轻松地添加新的
Wordable
。根据您的第二个建议,您需要进行迁移,为每个新的
Wordable
添加一列。谢谢,因为您是第一个,我将将此作为答案。@stpn,在Ruby(而不是sql)中附加列表时,您将无法链接sql并对结果集进行分页@stpn Kandaboggu的解决方案更好。谢谢,这是完美的。请您解释一下如果重新加载
,则
=nil的作用是什么?非常感谢。
故事
对象将结果缓存在名为
@words
的实例变量中。在某些情况下,您可能希望取消缓存。您可以通过传递
true来完成此操作
reload
参数的值。哦,我明白了,谢谢。我明白了,如果需要,可以从控制台或rake任务访问此选项。
story.words # returns line and phrase words
story.words.limit(5)