如何为Foo创建表迁移并且属于许多Foos?

时间:2015-07-12 18:12:19

标签: ruby-on-rails ruby-on-rails-4

假设我有一个Person模型,一个人可以有多个孩子,但也有多个父母。

使用def fileCount(fname): #counting variables d = {"lines":0, "words": 0, "lengths":[]} #file is opened and assigned a variable with open(fname, 'r') as f: for line in f: # split into words spl = line.split() # increase count for each line d["lines"] += 1 # add length of split list which will give total words d["words"] += len(spl) # get the length of each word and sum d["lengths"].append(sum(len(word) for word in spl)) return d def main(): fname = input('Enter the name of the file to be used: ') data = fileCount(fname) print ("There are {lines} lines in the file.".format(**data)) print ("There are {} characters in the file.".format(sum(data["lengths"]))) print ("There are {words} words in the file.".format(**data)) # enumerate over the lengths, outputting char count for each line for ind, s in enumerate(data["lengths"], 1): print("Line: {} has {} characters.".format(ind, s)) main() 创建一个联接表,会给我这个:

rails generate migration CreateJoinTablePersonPerson person person

运行上述迁移显然会导致:class CreateJoinTablePersonPerson < ActiveRecord::Migration def change create_join_table :people, :people do |t| # t.index [:person_id, :person_id] # t.index [:person_id, :person_id] end end end

如何为拥有并属于许多人的表创建表迁移?我是应该使用habtm,还是应该使用某种“有很多通过”的结构?

1 个答案:

答案 0 :(得分:1)

你想要多对多的自我联想。

请创建一个单独的模型名称:parent_child,其中有两个外键。

1)parent_id

2)child_id

因此,对于每个关系,例如:对于父项的新条目,child_id是self.id,而parent_id是父级,对于子级关系,parent_id:self.id,而child_id是子级。

你应该添加迁移。

 rails g model parent_child

这将导致迁移,向其添加列parent_id和child_id。

  class CreateTableParentChildren < ActiveRecord::Migration
      def change
          create_table :parent_children do |t|
            t.integer :parent_id
            t.integer :child_id
          end
         #add indexes on both
      end
  end

现在在父类中。你应该添加这样的东西。

class Person < ActiveRecord::Base

   has_many :children, class_name: "ParentChild", foreign_key: "parent_id"
   has_many :parents,  class_name: "ParentChild", foreign_key: "child_id" 
end

我希望这个想法可以帮助你实现你想要的东西。