2012-01-05 42 views
1

以下模型對讀取,更新和刪除操作正常,但不適用於創建。ruby​​ rails 3.0.x has_many通過異常創建,其他操作正常工作

class Space < ActiveRecord::Base 
    has_many :space_prices, :dependent => :destroy 
    accepts_nested_attributes_for :space_prices, :allow_destroy => true 
    has_many :space_price_availabilities, through: :space_prices, :order => "day_of_week, begin_time", read_only: true 
end 

class SpacePrice < ActiveRecord::Base 
    belongs_to :space 
    has_many :space_price_availabilities, inverse_of: :space_price, :dependent => :destroy, :order => "day_of_week, begin_time" 
    accepts_nested_attributes_for :space_price_availabilities, :allow_destroy => true 
end 

class SpacePriceAvailability < ActiveRecord::Base 
    belongs_to :space_price 
end 

我知道解決方法是實施Space.space_price_availabilities方法。僅僅總是引用Space.space_prices.space_price_availabilities b/c是不夠的,我需要將整個列表展平並排序。

如果我註釋掉has_many:在Space中,我可以創建新的空間。然後,如果我取消has_many的註釋:通過Space,我可以閱讀並更新它們。只有在創建時纔會出現以下異常。

ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection 

檢查日誌,正在生成並調用正確的SQL,但接着命中此異常並將其回滾。

任何想法?我真的很想知道我是否錯過了鐵軌協會的一些基本內容。它看起來很直截了當。該模型與API文檔中的示例基本相同。

回答

3

添加:autosave => false

has_many :space_price_availabilities, autosave: false, 
    inverse_of: :space_price, :dependent => :destroy, 
    :order => "day_of_week, begin_time", autosave: false 
+0

賓果!這有點複雜。我也應該包含模式定義。連接表(SpacePrice)只有FK到它的子表,所以它不是一個真正的多對多連接表。此外,由於此關聯只能通過SQL加載,因此在CREATE循環期間無法用於驗證方法,因爲父對象尚未保留。我猜。請注意,我發現在SpacePriceAvailability上添加了反向has_one:through =>:space_price也解決了異常。我正在使用它們,一定要確定。 – pduey 2012-01-06 00:07:36