您好,感謝您提前給予幫助。RoR:在購買的產品和用戶之間建立關係
我想在保存訂單時創建用戶和產品(pdf)之間的關係。
class PDF
has_many :line_items
end
class LineItem
belongs_to :pdf
belongs_to :cart
end
class Cart
has_many :line_items
has_one :order
end
class Order
belongs_to :cart
end
在用戶購買line_item時,我想通過用戶和pdf之間的連接模型(pdf_relationships)創建關係。
我正試圖在給定的購物車中找到每個PDF(由foreign_key line_item.pdf_id找到),並在用戶和購物車中的每個pdf之間創建pdf_relationships。我將使用戶的ID爲所有者ID,並使pdf的ID爲owned_id。
我的訂單控制器看起來是這樣的:
def create
@order = current_cart.build_order(params[:order])
@order.ip_address = request.remote_ip
if @order.save
if @order.purchase
render :action => "success"
else
render :action => "failure"
end
else
render :action => 'new'
end
end
什麼我遇到的麻煩是:
class Order
belongs_to :cart
before_save :create_owner
***def create_owner
self.cart.line_items.each do |item|
pdf.find_by_item_pdf_id(:pdf_id)
current_user.pdf_relationships.build(:owned_id => pdf.id)
end
end***
end
這裏是我的用戶模型:
class User
has_many :line_items
has_many :pdf_relationships, foreign_key: :owner_id, :dependent => :destroy
has_many :pdfs, foreign_key: :user_id, dependent: :destroy
has_many :pdf_ownings, :through => :pdf_relationships, :source => :owned
def owning?(owned)
pdf_relationships.find_by_pdf_owned_id(owned)
end
def own!(owned)
pdf_relationships.create!(:owned_id => owned.id)
end
def unown!(owned)
pdf_relationships.find_by_pdf_owned_id(owned).destroy
end
我希望這已經夠清楚了。我一直試圖弄清楚這個問題,現在肯定是想成爲一名新手。暗示性的讀物也絕對受歡迎!
我想我一定是在正確的方向前進。我想,當我嘗試通過遍歷購物車中的每個line_item(cart.line_item.pdf_id.each ...)來查找pdf並查看每個line_item.pdf_id時,問題就出現了。一旦我得到這些ID,那麼我可以創建PDF關係。總的來說,我需要採取每個pdf.id這是line_item.pdf_id並將其作爲owned.id。 – Jches 2012-02-11 03:55:08
你還在收到錯誤?你能使用我的示例代碼嗎?如果不是,你的'User'模型是什麼樣的? – Brandan 2012-02-11 04:13:19
是的,我仍然有錯誤。我編輯了我的問題並添加了用戶模型。我的代碼def create_owner在訂單模型中甚至遠程更正? – Jches 2012-02-11 20:56:12