在ruby中为依赖表创建迁移

时间:2011-12-08 09:04:12

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

在我的rails应用程序中,我有一个依赖于角色模型的用户模块。两者都是通过user_role_assignment模型集成的。用户可以通过用户角色分配关联多个角色。

我需要生成迁移来创建一些默认用户。 我面临的问题是,如果我尝试通过控制台创建用户,我会收到一条错误消息“角色不能为空。

u=User.create(:name => "ramyameena", :email => "ramyameena@sandvine.com",:password=>"sandvine",:roles=>{:id=>2,:name=>"Tester"})
=> #<**User id: nil**, name: "ramyameena", created_at: nil, updated_at: nil, email: "ramyameena@sandvine.com", encrypted_password: "$2a$10$qIfRLKZlxviag9E0Gzvp8e3VKkOCaXraP7PnJC6vGMN....", reset_password_token: nil, remember_token: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil>

irb(main):012:0> u.errors.inspect
=> "#<OrderedHash **{:roles=>[\"can't be blank\"]**}>"

我的用户型号:

class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :name, :presence => true, :uniqueness => true
validates :roles, :presence => true
has_many :user_role_assignments
has_many :roles, :through => :user_role_assignments
has_many :tester_release_assignments
has_many :releases, :through => :tester_release_assignments
has_many :releases
has_many :ic_runs
accepts_nested_attributes_for :user_role_assignments
attr_accessible :email, :name, :password, :password_confirmation, :role_ids

1 个答案:

答案 0 :(得分:2)

您有accepts_nested_attributes_for :user_roles_assignments但是在创建时,您传递的是角色,而不是user_roles_assignments。我会检查你是不是错过了accepts_nested_attributes_for :roles或某种帮助方法......

或者,您需要单独执行这些角色。例如

u = User.new(:name => "ramyameena", :email => "ramyameena@sandvine.com",:password=>"sandvine")
u.roles.build(:id=>2,:name=>"Tester")
u.save