我一直有一點難以理解整個有很多概念以及它如何在Rails中工作,我認爲它爲你做腿部工作,因爲我習慣於手動建立關聯。我目前有一個結算系統,我正在嘗試創建一個訂單部分,顯然我的訂單必須有很多產品,所以我已經將數據庫規範化爲第三範式,以便訂單和產品通過另一個表格命名爲訂購產品,此表格包含訂單的ID和產品的ID以及訂購產品的數量。我已經根據我所瞭解的has_Many創建了模型:通過代碼學校教程的Rails,但是我已經完全複製了它的樣子,但是地雷和它們之間必定有某種區別。這是我目前擁有的模型文件:Rails:麻煩有很多通過關係
訂貨型號:
class Order < ActiveRecord::Base
attr_accessible :ClientID, :OrderTotal
has_many :orderedproducts
has_many :products, through: :orderedproducts, :source => :product
end
訂購的產品型號:
class Orderedproduct < ActiveRecord::Base
attr_accessible :OrderID, :ProductID, :QuantityOrdered
belongs_to :order
belongs_to :product
end
產品型號:
class Product < ActiveRecord::Base
#This line makes these elements accessible outside of the class.
attr_accessible :ProductName, :ProductPrice, :ProductQuantity, :ProductSupplier
has_many :orderedproducts
has_many :orders, through: :orderedproducts, :source => :order
#These attributes ensure that the data entered for each element is valid and present.
validates_presence_of :ProductName
validates_presence_of :ProductPrice
validates_numericality_of :ProductPrice
validates_presence_of :ProductQuantity
validates_numericality_of :ProductQuantity
validates_presence_of :ProductSupplier
end
我添加源屬性因爲我在控制檯中發現錯誤,提示我應該將源屬性添加到h as_many:通過線路。這是我收到的控制檯中的錯誤,當我嘗試將產品添加到訂單:
irb(main):017:0> order.products = Product.find(4)
Product Load (0.3ms) SELECT `products`.* FROM `products` WHERE `products`.`id` = 4 LIMIT 1
ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :ProductID in model Orderedproduct. Try 'has_many :products, :through => :orderedproducts, :source => <name>'. Is it one of :order or :product?
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/reflection.rb:509:in `check_validity!'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations/association.rb:26:in `initialize'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations/collection_association.rb:24:in `initialize'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations/has_many_through_association.rb:10:in `initialize'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations.rb:160:in `new'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations.rb:160:in `association'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/activerecord-3.2.13/lib/active_record/associations/builder/association.rb:51:in `block in define_writers'
from (irb):17
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/railties-3.2.13/lib/rails/commands/console.rb:47:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/railties-3.2.13/lib/rails/commands/console.rb:8:in `start'
from /usr/local/rvm/gems/ruby-2.0.0-p0/gems/railties-3.2.13/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'