我有以下脚本,它向我展示了 has_manyroles=
属性始终以持久的方式工作。
我的问题是:
1)这种行为背后的原因是什么:为什么 has_many 属性在它们被设置的那一刻就被持久化了?为什么与常规属性行为有这种差异(name
在以下脚本中)?
2)我可以编写我的自定义roles=
设置器,以便我可以将 fxassign_attributes
用于一堆模型属性(包括角色=)而无需保留角色关联吗?如果 Rails > 3.2 有可能,我会很感激一个例子?
这是脚本:
gem 'rails', '>=3.2.0' # change as required
gem 'sqlite3'
require 'active_record'
require 'logger'
puts "Active Record #{ActiveRecord::VERSION::STRING}"
ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => ':memory:'
)
ActiveRecord::Schema.define do
create_table :users, :force => true do |t|
t.string :name
end
create_table :user_roles, :force => true do |t|
t.integer :user_id
t.integer :role_id
end
create_table :roles, :force => true do |t|
t.string :name
end
end
# Create the minimal set of models to reproduce the bug
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, :through => :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
class Role < ActiveRecord::Base
end
r = Role.create(:name => 'admin')
u = User.create
# roles= persists its value, name= does not
u.assign_attributes({ :roles => [r], :name => 'Stanislaw' })
# The same behavior is produced by:
# u.attributes=
# u.roles=
puts "name attribute: #{u.name}"
puts "many roles #{u.roles}"
u.reload
puts "name attribute: #{u.name}"
puts "many roles #{u.roles}" # I see admin role and I want to achieve behavior that I would not see it