2017-05-14 45 views
0

現在我有三種模型:Product,Cart,CartItem。下面是相關的方法和關聯:find_by_product_id(params [:id])vs find_by(params [:product_id])有什麼區別

cart.rb

class Cart < ApplicationRecord 
    has_many :cart_items 
    has_many :products, :through => :cart_items, :source => :product 

cart_item.rb(它有2個相關的整數列,:product_id & :cart_id

class CartItem < ApplicationRecord 
    belongs_to :cart 
    belongs_to :product 

application_controller。 rb

class ApplicationController < ActionController::Base 

    helper_method :current_cart 

    def current_cart 
     @current_cart ||= find_cart 
    end 

    private 

    def find_cart 
     cart = Cart.find_by(id: session[:cart_id]) 
     if cart.blank? 
     cart = Cart.create 
     end 
     session[:cart_id] = cart.id 
     return cart 
    end 
end 

carts_controller.rb我所限定的方法來刪除在推車#索引頁特定cart_item:

class CartsController < ApplicationController 

    def destroy_one 
     @cart_item = current_cart.cart_items.find_by_product_id(params[:id]) 
     @product = @cart_item.product 
     @cart_item.destroy 
    redirect_to :back 

destroy_one方法的第一行,我可以用find_by_product_id(params[:id])得到正確的cart_item

然後我試着find_by(product_id: params[:id]),它也可以。

但是,如果我使用find_by(params[:product_id]),出現了問題。當我點擊刪除按鈕時,它不會引發異常,但會刪除其他cart_item。似乎欄杆隨機挑選cart_item並將其刪除。


顯然,find_by(params[:product_id])在這裏工作不正確。

我的問題是:

在這種情況下,我混淆軌如何找到一步正確的對象步驟?在一個購物車中,有很多cart_items和產品,通過使用:product_id來合理地定位cart_item。但是,什麼是之間的區別:VS find_by(params[:product_id])

find_by_product_id(params[:id])分別,他們是如何工作的?

回答

1

問題是您使用的是find_by(params[:product_id])錯誤。你必須通過你要搜索的明確,像這樣的關鍵:

find_by(product_id: params[:product_id]) 

User.find_by(id: 1) 
-> User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]] 

分別,你可以使用它作爲你說已經:

find_by_product_id(params[:product_id]) 

User.find_by_id(1) 
-> User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]] 

正如你所看到的,這兩種方法產生非常相同SQL查詢。

+0

謝謝菲利普,在閱讀Rails指南並做了幾個實驗後,現在我可以理解你所說的了。問題是我誤解了軌道檢索數據的方式。 – Caven

+0

不客氣:) –

相關問題