2014-01-08 55 views
0

兩個表與另一個表具有has_one關係»反饋«通過多態關聯。Ruby on Rails 4:多態關聯拋出InverseOfAssociationNotFoundError

# Class Request 
class Request < ActiveRecord::Base 
    belongs_to :user, inverse_of: :requests 
    has_one :feedback, as: :feedbackable 
end 

# Class Acceptance 
class Acceptance < ActiveRecord::Base 
    belongs_to :user, inverse_of: :acceptances 
    has_one :feedback, as: :feedbackable 
end 

# Class Feedback 
class Feedback < ActiveRecord::Base 
    belongs_to :feedbackable, polymorphic: true 
    belongs_to :user, inverse_of: :feedbacks 
end 

然而,試圖創造相關要麼請求或接受反饋時,控制檯拋出我的錯誤。以下是我試圖創建一個反饋:

# First way 
feedback = request.create_feedback(user_id: 2, message: "Hey, good driver!") 

# Second way 
feedback = Feedback.create(user_id: 1, message: "Hey, good driver!") 
#user_id describes the user the feedback addresses 

request = Request.create(user_id: 2) 
#user_id describes the user the request comes from 

request.feedback = feedback 

這是一個被拋出的錯誤:

ActiveRecord::InverseOfAssociationNotFoundError: Could not find the inverse association for feedback (:request in Feedback)

在此先感謝,我一直在到處搜索,並沒有發現類似的問題:小號

你可能想知道我的數據庫是什麼樣子:

class CreateAcceptances < ActiveRecord::Migration 
    def change 
    create_table :acceptances do |t| 
     t.references :user, index: true 

     t.timestamps 
    end 
    end 
end 

class CreateRequests < ActiveRecord::Migration 
    def change 
    create_table :requests do |t| 
     t.references :user, index: true 

     t.timestamps 
    end 
    end 
end 

class CreateFeedbacks < ActiveRecord::Migration 
    def change 
    create_table :feedbacks do |t| 
     t.references :feedbackable, polymorphic: true 
     t.references :user, index: true 
     t.string :message 
     t.timestamps 
    end 
    end 
end 

回答

1

是你一直郵政代碼d究竟是在運行什麼來產生錯誤信息?基於錯誤我本來期望下面的請求代碼:

# Class Request 
class Request < ActiveRecord::Base 
    belongs_to :user, inverse_of: :requests 
    has_one :feedback, as: :feedbackable, inverse_of: :request 
end 

特別是你告訴其他的ActiveRecord往裏反饋的:它是沒有找到has_one :feedback, inverse_of: :request請求關聯。這可以在任何主動記錄模型上,不一定是request.rb。我在Rails 4.0.2中遇到了完全相同的消息,並刪除了inverse_of:解決了這個問題。