Permalink
Browse files

Don't use mass-assignment protection when setting foreign keys or ass…

…ociation conditions on singular associations. Fixes #481 (again).
  • Loading branch information...
1 parent b210d9e commit 6e466f17c3d0d06cc364c27fd844a66fb4a89aa2 @jonleighton jonleighton committed May 12, 2011
@@ -18,15 +18,22 @@ def writer(record)
end
def create(attributes = {}, options = {})
- new_record(:create, attributes, options)
+ build(attributes, options).tap { |record| record.save }
end
def create!(attributes = {}, options = {})
build(attributes, options).tap { |record| record.save! }
end
def build(attributes = {}, options = {})
- new_record(:build, attributes, options)
+ record = reflection.build_association
+ record.assign_attributes(
+ scoped.scope_for_create.except(klass.primary_key),
+ :without_protection => true
+ )
+ record.assign_attributes(attributes, options)
+ set_new_record(record)
+ record
end
private
@@ -43,13 +50,6 @@ def replace(record)
def set_new_record(record)
replace(record)
end
-
- def new_record(method, attributes, options)
- attributes = scoped.scope_for_create.merge(attributes || {})
- record = reflection.send("#{method}_association", attributes, options)
- set_new_record(record)
- record
- end
end
end
end
@@ -4,6 +4,7 @@
require 'models/company'
require 'models/ship'
require 'models/pirate'
+require 'models/car'
require 'models/bulb'
class HasOneAssociationsTest < ActiveRecord::TestCase
@@ -377,4 +378,36 @@ def test_deprecated_association_loaded
assert_equal firm.association(:account).loaded?, firm.account_loaded?
end
end
+
+ def test_association_keys_bypass_attribute_protection
+ car = Car.create(:name => 'honda')
+
+ bulb = car.build_bulb
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.build_bulb :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.create_bulb
+ assert_equal car.id, bulb.car_id
+
+ bulb = car.create_bulb :car_id => car.id + 1
+ assert_equal car.id, bulb.car_id
+ end
+
+ def test_association_conditions_bypass_attribute_protection
+ car = Car.create(:name => 'honda')
+
+ bulb = car.build_frickinawesome_bulb
+ assert_equal true, bulb.frickinawesome?
+
+ bulb = car.build_frickinawesome_bulb(:frickinawesome => false)
+ assert_equal true, bulb.frickinawesome?
+
+ bulb = car.create_frickinawesome_bulb
+ assert_equal true, bulb.frickinawesome?
+
+ bulb = car.create_frickinawesome_bulb(:frickinawesome => false)
+ assert_equal true, bulb.frickinawesome?
+ end
end
@@ -4,6 +4,9 @@ class Car < ActiveRecord::Base
has_many :foo_bulbs, :class_name => "Bulb", :conditions => { :name => 'foo' }
has_many :frickinawesome_bulbs, :class_name => "Bulb", :conditions => { :frickinawesome => true }
+ has_one :bulb
+ has_one :frickinawesome_bulb, :class_name => "Bulb", :conditions => { :frickinawesome => true }
+
has_many :tyres
has_many :engines
has_many :wheels, :as => :wheelable

0 comments on commit 6e466f1

Please sign in to comment.