2015-10-27 34 views
1

我有2個車型,車和LINE_ITEM:車驗證的最大項目

cart.rb & line_item.rb

class Cart < ActiveRecord::Base 
    has_many :line_items, dependent: :destroy 
    belongs_to :user 

class LineItem < ActiveRecord::Base 
belongs_to :cart 
belongs_to :user 

application_controller.rb

def current_cart 
    Cart.find(session[:cart_id]) 
    rescue ActiveRecord::RecordNotFound 
    cart = current_user.cart.create 
    session[:cart_id] = cart.id 
    cart 
end 

如何添加驗證到我的購物車,以便用戶最多隻能將5件物品添加到購物車中?目前我有這個代碼,但它不工作?

def maximum_items_not_more_than_5 
    if line_items.count > 5 
     errors.add(:line_items, "must be less than 5") 
    end 
end 

回答

0

爲什麼line_item屬於user? ?毫無疑問這將是item

#app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :carts 
end 

#app/models/cart.rb 
class Cart < ActiveRecord::Base 
    belongs_to :user 

    has_many :line_items, inverse_of: :cart 
    has_many :items, through: :line_items 

    validate :max_line_items 

    private 

    def max_line_items 
     errors.add(:tags, "Too many items in your cart!!!!!!") if line_items.size > 5 
    end 
end 

#app/models/line_item.rb 
class LineItem < ActiveRecord::Base 
    belongs_to :cart, inverse_of: :line_items 
    belongs_to :item #-> surely you want to specify which item is in the cart? 
end 

#app/models/item.rb 
class Item < ActiveRecord::Base 
    has_many :line_items 
    has_many :carts, through: :line_items 
end 

驗證

這肯定是在validation的領域,特別是custom method

#app/models/model.rb 
class Model < ActiveRecord::Base 
    validate :method 

    private 

    def method 
     ## has access to all the instance attributes 
    end 
end 

我也把inverse_of到組合。

你可以看到這是如何工作在這裏:https://stackoverflow.com/a/20283759/1143732

具體來說,它可以讓你從調用特定型號parent/child對象,從而使您可以打電話驗證居住在這些文件&方法。

在你的情況下,它可能會謹慎地爲line_item模型添加驗證 - 指定個別數量或其他東西。您可以通過設置正確的inverse_of

1

這是一種方式,我會嘗試:

class LineItem < ActiveRecord::Base 
belongs_to :cart, validate: true # enables validation 

然後車模型裏面,寫你自己喜歡的自定義驗證:

class Cart < ActiveRecord::Base 
    has_many :line_items, dependent: :destroy 
    validate :maximum_items_not_more_than_5 # using custom validation 

    private 

    def maximum_items_not_more_than_5 
    if line_items.count > 5 
     errors.add(:base, "must be less than 5") 
    end 
    end 
+0

Arup直接從您的cart模型中調用此模型中的驗證。先生,你正在軌道上取得驚人的進步! –