2011-05-11 103 views
0

我有兩個模型,用戶和事件。每個事件都有一個唯一的用戶角色管理員。 當我試圖訪問@ user.administered_events以獲取顯示此消息的事件時。Rails一對多關聯與class_name問題

的ActiveRecord :: StatementInvalid:Mysql的::錯誤:未知列在 'where子句' 'events.user_id':SELECT events * FROM events WHERE(events .user_id = 5)

Rails正在嘗試訪問來自事件的user_id而不是admin_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 

回答

1

嘗試使用:你的聲明關聯時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文檔:

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.

0

嘗試:

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