我試圖做一個has_many關係工作的對象來創建。添加項目到has_many關係的創建
這是一個簡單的例子,儘管通過網絡進行了很多努力和研究,但我找不到爲什麼我的代碼無法正常工作。
我有以下類(注:某些變量,使用法語名稱):
class Comptes::Category < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
accepts_nested_attributes_for :categorizations
has_many :transactions, through: :categorizations
validates :nom, presence: true, uniqueness: true
end
class Comptes::Transaction < ActiveRecord::Base
has_many :categorizations, dependent: :destroy
accepts_nested_attributes_for :categorizations
has_many :categories, through: :categorizations
... # some validations
end
class Comptes::Categorization < ActiveRecord::Base
belongs_to :transaction
belongs_to :category
validates :transaction, presence: true
validates :category, presence: true
end
類別和交易的基本模型和分類是專門爲協會(這是一個基本賬戶 - 交易系統)。
我能做些什麼是創建一個事務和一個類別,然後用類別填充transaction.categories(事務有一個id)。
我不能做是:
transaction = Comptes::Transaction.new ...
category = Comptes::Category.first
transaction.categories << category
# OR
transaction.categorizations.build category: category
# OR
# use categorizations_attributes in and accepts_nested_attributes_for.
非常感謝您的任何幫助
編輯:這是在軌道4.0.0 做,我發現這個問題來自何處Comptes :: Categorization中的驗證。 這可防止在事務或類別尚不存在的情況下創建新分類。
更新(2014年8月18日):問題來自分類中的驗證,這會阻止在沒有現有事務和類別的情況下創建關聯。這可能是rails 4.0.0中的一個問題。要看...
其實,這只是一個複製錯誤。交易也屬於模塊Comptes。我會更新我的問題。 – Kineolyan