Is there any way to avoid automatically saving object while assigning collection attributes(collection_singular_ids=ids method)?
for example, I have the following Test and Package model, Package has many tests. User can build package bundle with number of tests.
# test.rb
class Test < ActiveRecord::Base
end
# package.rb
class Package < ActiveRecord::Base
has_many :package_tests
has_many :tests, :through => :package_tests
belongs_to :category
validate :at_most_3_tests
private
# tests count will differ depends on category.
def at_most_3_tests
errors.add(:base, 'This package should have at most three tests') if test_ids.count > 3
end
end
# package_test.rb
class PackageTest < ActiveRecord::Base
belongs_to :package
belongs_to :test
validates_associated :package
end
No issue on validation when package object is new.
1.9.2 :001> package = Package.new(:name => "sample", :cost => 3.3, :test_ids => [1,2,3,4])
=> #<Package id: nil, name: "sample", cost: 3.3>
1.9.2 :002> package.test_ids
=> [1, 2, 3, 4]
1.9.2 :003> package.save
=> false
1.9.2 :004> package.save!
ActiveRecord::RecordInvalid: Validation failed: This package should have at most three tests
1.9.2: 005> package.test_ids = [1,2]
=> [1, 2]
1.9.2 :005> package.save!
=> true
But I couldn't hit at_most_3_tests method with persisted package object.
Join table record is created immediately when assigning test ids
1.9.2: 006> package
=> #<Package id: 1, name: "sample", cost: 3.3>
1.9.2: 007> package.test_ids
=> [1,2]
1.9.2: 007> package.test_ids = [1,2,3,4,5]
=> [1,2,3,4,5]
1.9.2: 008> package.test_ids
=> [1,2,3,4,5]
Client requirement is drop-down interface for selection of multiple tests in package form and also used select2 jquery plugin for drop-down. Rhmtl code looks like
<%= form_for @package do |f| %>
<%= f.text_field :name %>
<div> <label>Select Tests</label> </div>
<div>
<%= f.select "test_ids", options_for_select(@tests, f.object.test_ids), {}, { "data-validate" => true, :multiple => true} %>
</div>
Please help me to fix this issue.