2010-01-28 26 views
5

Xin chào, tôi đang sử dụng has_and_belongs_to_many trong một mô hình. Tôi muốn đặt valitor của sự hiện diện cho các loại. và đặt số lượng tối đa các loại trên mỗi lõi thành 3xác thực sự hiện diện của has_and_belongs_to_many

class Core < ActiveRecord::Base 
    has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id' 
end 

làm cách nào tôi có thể làm?

nhờ

Trả lời

6
validate :require_at_least_one_kind 
validate :limit_to_three_kinds 

private 

def require_at_least_one_kind 
    if kinds.count == 0 
    errors.add_to_base "Please select at least one kind" 
    end 
end 

def limit_to_three_kinds 
    if kinds.count > 3 
    errors.add_to_base "No more than 3 kinds, please" 
    end 
end 
2

Bạn có thể thử một cái gì đó như thế này (thử nghiệm on Rails 2.3.4):

class Core < ActiveRecord::Base 
    has_and_belongs_to_many :kinds, :foreign_key => 'core_id', :association_foreign_key => 'kind_id' 
    validate :maximum_three_kinds 
    validate :minimum_one_kind 

    def minimum_one_kind 
    errors.add(:kinds, "must total at least one") if (kinds.length < 1) 
    end 

    def maximum_three_kinds 
    errors.add(:kinds, "must not total more than three") if (kinds.length > 3) 
    end 
end 

... mà làm theo cách sau:

require 'test_helper' 

class CoreTest < ActiveSupport::TestCase 

    test "a Core may have kinds" do 
    core = Core.new 
    3.times { core.kinds << Kind.new } 

    assert(core.save) 
    end 

    test "a Core may have no more than 3 kinds" do 
    core = Core.new 
    4.times { core.kinds << Kind.new } 
    core.save 

    assert_equal(1, core.errors.length) 
    assert_not_nil(core.errors['kinds']) 
    end 

    test "a Core must have at least one kind" do 
    core = Core.new 
    core.save 

    assert_equal(1, core.errors.length) 
    assert_not_nil(core.errors['kinds']) 
    end 
end 

Rõ ràng là ở trên không đặc biệt là DRY hoặc sẵn sàng sản xuất, nhưng bạn có ý tưởng.

+1

Lưu ý rằng phương thức xác thực không được chấp nhận trong 2.0.3, nhưng nó không nói có lợi cho điều gì. Bất cứ ai có thể làm rõ? – tadman

Các vấn đề liên quan