开发者

Rails one to many association with class_name problem

开发者 https://www.devze.com 2023-03-05 01:48 出处:网络
I have two models, User and Event. Every event has a unique admin who is a User role. When Im trying to access @event.admin i get my admin user but if Im trying to acc开发者_如何学Cess @user.administe

I have two models, User and Event. Every event has a unique admin who is a User role. When Im trying to access @event.admin i get my admin user but if Im trying to acc开发者_如何学Cess @user.administered_events to get the events this message is displayed.

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

Rails is trying to access user_id from Event instead of admin_id. What I`m doing wrong?

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


Try using the :foreign_key option when declaring your associations:

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

From the Rails documentation:

By convention, Rails guesses that the column used to hold the foreign key on the other model is the name of this model with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly.


Try:

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

精彩评论

暂无评论...
验证码 换一张
取 消