Rake任务外键分配在多对多关系中

时间:2015-03-14 19:13:04

标签: ruby-on-rails

我有两个表:组和关键字。它们通过名为Assignments的另一个表具有多对多关系。我有一个rake任务,我生成随机关键字,将关键字保存到关键字表并将其分配给当前组的关键字。代码看起来像这样(我使用了类似于我在控制台中使用的语法;但是,我不确定它的正确性):

Group.populate 30 do |group|        
  Faker::Lorem.words(rand(3..7)).each do |key|
    k = Keyword.create(name: key)
    group.keywords << k
  end 
end

<<正在返回此错误:NoMethodError: undefined method&lt;&lt;'`。

如果我在控制台中运行内部两行,我得到了我期望的结果(注意:我简化了以下模型,因此您将在日志中看到更多键,但忽略它):

   (0.1ms)  begin transaction
  SQL (2.0ms)  INSERT INTO "keywords" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "bla"], ["created_at", "2015-03-14 18:25:29.179793"], ["updated_at", "2015-03-14 18:25:29.179793"]]
   (1.2ms)  commit transaction
 => #<Keyword id: 1, name: "bla", created_at: "2015-03-14 18:25:29", updated_at: "2015-03-14 18:25:29">

   (0.2ms)  begin transaction
  SQL (1.8ms)  INSERT INTO "assignments" ("group_id", "keyword_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["group_id", 1], ["keyword_id", 1], ["created_at", "2015-03-14 18:26:53.650257"], ["updated_at", "2015-03-14 18:26:53.650257"]]
   (0.8ms)  commit transaction
 => #<ActiveRecord::Associations::CollectionProxy [#<Keyword id: 1, name: "bla", created_at: "2015-03-14 18:25:29", updated_at: "2015-03-14 18:25:29">]>

Group模型如下所示:

class Group < ActiveRecord::Base
    has_many :assignments, dependent: :destroy
    has_many :keywords, through: :assignments, dependent: :destroy
end

关键字模型如下所示:

class Keyword < ActiveRecord::Base
    has_many :assignments
    has_many :groups,    through: :assignments 
end

Assignment模型如下所示:

class Assignment < ActiveRecord::Base
    belongs_to :group
    belongs_to :keyword
end

如何修改此代码以按预期工作?

2 个答案:

答案 0 :(得分:0)

试试这个

class Group < ActiveRecord::Base
  has_many :assignments, dependent: :destroy
  has_many :active_assignments, dependent: :destroy, class_name: "Assignment"
  has_many :keywords, through: :active_assignments, source: :keyword

class Keyword < ActiveRecord::Base
    has_many :assignments, dependent: :destroy
    has_many :groups, through: :assignments
end 

class Assignment < ActiveRecord::Base
    belongs_to :group
    belongs_to :keyword
end    


Group.populate 30 do |group|        
   Faker::Lorem.words(rand(3..7)).each do |key|
      group.keywords << Keyword.create(name: key)
   end 
end

答案 1 :(得分:0)

我在程序中发现了问题。即使这是我的一个愚蠢的错误,我会留下问题,并报告错误,以防将来任何人陷入同样的​​问题。 我有这个错误,因为我的组表中有一个名为关键字的字段,这当然与关键字表(与组有多对多关系)冲突。在我决定创建多对多关系之前我有这个领域,我忘了删除它。然后,当你输入类似这个命令group.keywords << Keyword.create(name: key)的东西时,你会得到这个奇怪的错误:NoMethodError: undefined method<<

但是,修复此错误不会使rake任务运行。这是因为Group.populate返回一个Populator对象。如果您运行此任务,则会收到此错误:NoMethodError: undefined method keywords for #<Populator::Record:0x007fa1ee78fba8>。要解决这个问题,我必须在任务中手动分配外键,如下所示:

Group.populate 30 do |group|        
   Faker::Lorem.words(rand(3..7)).each do |key|
        k = Keyword.create(name: key)
        a = Assignment.create(keyword_id: k.id, group_id: group.id)
   end 
end

将按预期运行。