【问题标题】:Rails one to many association with class_name problemRails 与 class_name 问题的一对多关联
【发布时间】:2011-08-23 17:28:11
【问题描述】:

我有两个模型,用户和事件。每个事件都有一个独特的管理员,他是用户角色。 当 Im trying to access @event.admin i get my admin user but if Im 尝试访问 @user.administered_events 以获取事件时,将显示此消息。

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'events.user_id' in 'where clause': SELECT events.* FROM events WHERE (events.user_id = 5)

Rails 正在尝试从 Event 而不是 admin_id 访问 user_id。我做错了什么?

class User < ActiveRecord::Base
  has_many :administered_events, :class_name => "Event" 
end

class Event < ActiveRecord::Base
  belongs_to :admin, :class_name => "User"
end

class CreateEvents < ActiveRecord::Migration
  def self.up
    create_table :events do |t|
      t.string :title
      t.date :date
      t.string :status
      t.integer :admin_id

      t.timestamps
    end
  end

  def self.down
    drop_table :events
  end
end

【问题讨论】:

    标签: ruby-on-rails activerecord associations one-to-one


    【解决方案1】:

    试试:

    class User < ActiveRecord::Base
      has_many :administered_events, :class_name => "Event" , foreign_key => "admin_id"
    end
    

    【讨论】:

      【解决方案2】:

      在声明关联时尝试使用 :foreign_key 选项:

      class User < ActiveRecord::Base
        has_many :administered_events, :class_name => "Event", :foreign_key => "admin_id"
      end
      
      class Event < ActiveRecord::Base
        belongs_to :admin, :class_name => "User"
      end
      

      来自 Rails 文档:

      按照惯例,Rails 猜测 用于保存外键的列 另一个模型是这个的名字 添加后缀 _id 的模型。这 :foreign_key 选项可让您设置 直接外键的名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 1970-01-01
        • 2014-03-21
        • 1970-01-01
        相关资源
        最近更新 更多