【问题标题】:Rails 4 Active record circular dependency errorRails 4活动记录循环依赖错误
【发布时间】:2013-10-16 09:11:34
【问题描述】:

这些是我的桌子:

create_table :messages do |t|
  t.integer :type
  t.string :text
  t.datetime :sent_date
  t.string :sender
  t.timestamps
end

create_table :users do |t|
  t.integer :phone
  t.string :fullname
  t.string :profile_image
  t.timestamps
end

create_table :send_tos do |t|
  t.string :receiver
  t.belongs_to :message
  t.boolean :is_received
end

这些是模型类:

class User < ActiveRecord::Base
  has_many :send_tos, :foreign_key => 'receiver'
  has_many :messages, :foreign_key => 'sender'
end

class Message < ActiveRecord::Base
  belongs_to :user, :foreign_key => 'sender'
  has_many :send_tos
end

class Send_to < ActiveRecord::Base
  belongs_to :user, :foreign_key => "receiver"
  belongs_to :message
end

当我在 Rails 控制台上运行这些命令时:

m = Message.new
m.save
s = Send_to.new
s.message = m
s.save
m.send_tos

在命令m.send_tos之后我得到这个错误:

RuntimeError:自动加载常量时检测到循环依赖 发送到

为什么会出现此错误?我应该怎么做才能改变它?

【问题讨论】:

  • 尝试将Send_to 类的名称更改为SendTo。这遵循 Rails 为其关系假定的命名约定。它所在的文件名应该是send_to.rb
  • @Alex.Bullard 你能把你的评论写成答案吗
  • 当然,很高兴它成功了
  • 嗯不完全确定为什么你得到一个空集合。 s.save 是否返回真实?从s.message_id 返回什么?
  • 是的,就是这样。在调用m.send_tos 之前,我需要从数据库中获取对象。致电m = Message.first 解决了问题;)

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


【解决方案1】:

Send_to 类的名称更改为SendTo。这遵循 Rails 为其关系假定的命名约定。它所在的文件名应该是send_to.rb

【讨论】:

    猜你喜欢
    • 2016-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-07
    • 1970-01-01
    相关资源
    最近更新 更多