1

为什么我这样做时没有分配用户?

u1 = User.create( :username => "user1", :password => "testing", :email =>  "user1@email.com", :time_zone => "Tokyo")
u2 = User.create( :username => "user2", :password => "testing", :email =>  "user2@email.com", :time_zone => "Eastern Time (US & Canada)")
u3 = User.create( :username => "user3", :password => "testing", :email =>  "user3@email.com", :time_zone => "Singapore") # User that adds Private stuff only.

o1 = Owner.create!( :name => "Owner A", :about => "", :user_id => User.find_by_username("user1"), :private => false, without_protection: true )
o2 = Owner.create!( :name => "Owner B", :about => "", :user_id => User.find_by_username("user2"), :private => false, without_protection: true )
o3 = Owner.create!( :name => "Private Owner", :about => "", :user_id => User.find_by_username("user3"), :private => true, without_protection: true )

我得到错误:

$ rake db:seed
rake aborted!
Validation failed: User can't be blank

Tasks: TOP => db:seed
(See full trace by running task with --trace)

他们还有什么其他方法可以让我分配用户ID?

更新

所有者.rb

class Owner < ActiveRecord::Base
  attr_accessible :name, :about, :private
  belongs_to :user
  has_many :locations
  validates_presence_of :name
  validates_presence_of :user_id
  validates_inclusion_of :private, :in => [true, false]
  validates_length_of :name, :in => 3...50, :allow_blank => true
end

到目前为止,我已经尝试过:

:user_id => User.find_by_username("user1")
:user_id => u1
:user_id => u1.id
:user => User.find_by_username("user1")
:user => u1

更新 2

这有效,但仅user_id = 1适用于我的所有所有者:

o1 = Owner.new( :name => "Owner A", :about => "", :private => false )
o1.user_id = u1
o1.save!
4

1 回答 1

1

user尽管您没有包含模型的代码,但从验证错误来看,您似乎对Owner模型中的存在进行了验证。在您的Owner.create!行中,您正在传递user_id. 尝试将其更改为:

o1 = Owner.create!( :name => "Owner A", :about => "", :user => User.find_by_username("user1"), :private => false, without_protection: true )

或者,由于您刚刚创建了这些用户,您可以这样做:

o1 = Owner.create!( :name => "Owner A", :about => "", :user => u1, :private => false, without_protection: true )

附带说明一下,您可以通过两种方式传入关联,或者通过其 id ( :user_id => user.id) 或通过实际实例 ( :user => @user)。Rails 验证非常挑剔,所以如果你验证它会user寻找.useruser_iduser_id

于 2012-08-24T01:37:59.347 回答