无法在一对一关联Rails中分配关联对象

时间:2013-11-13 00:11:25

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

我有一个商家和用户模型定义为一对一的关联。

商家模式

class Merchant < ActiveRecord::Base
    has_one :user, dependent: :destroy

用户模型

class User < ActiveRecord::Base
    validates :username, uniqueness:{case_sensitive: false}
    belongs_to :gender
    belongs_to :merchant, dependent: :restrict_with_exception

性别模型

class Gender < ActiveRecord::Base
    has_many: users

创建User obj并将其保存到DB没有问题。将性别obj g分配给用户obj u也没有问题。

g = Gender.create(gender: "M")
u = User.create(username: "tester", first_name: "Tester", last_name: "Mac", email:"emadail@y.com", passwd:"passwddfaff ", salt: "fdafeagda", active: true, gender:g)

问题:无法将现有用户u分配给商家obj m

m = Merchant.create(user: u, company: "company")

它返回

DEPRECATION WARNING: You're trying to create an attribute `merchant_id'. 
Writing arbitrary attributes on a model is deprecated. Please just use `attr_writer`    etc. (called from irb_binding at (irb):17)

D, [2013-11-12T15:11:45.838908 #834] DEBUG -- :    (0.1ms)  COMMIT
D, [2013-11-12T15:11:45.839365 #834] DEBUG -- :    (0.1ms)  BEGIN
D, [2013-11-12T15:11:45.842261 #834] DEBUG -- :   SQL (0.4ms)  INSERT INTO `merchants`     (`company`, `created_at`, `updated_at`) VALUES ('company', '2013-11-12 23:11:45', '2013-11-12    23:11:45')
E, [2013-11-12T16:58:22.311452 #1032] ERROR -- : Mysql2::Error: Field 'user_id' doesn't have a default value: INSERT INTO `merchants` (`company`, `created_at`, `updated_at`) VALUES ('mystorebag', '2013-11-13 00:58:22', '2013-11-13 00:58:22')

我也尝试使用Merchant.new

m = Merchant.new
m.user = u
m.company = "com"
m.save

我得到了与上述相同的sql错误,但是,当我尝试m.user时,它会输出用户obj;使用m,它会将user属性输出为nil

正如Rail的API中的has_one方法所述

association=(associate) Assigns the associate object, extracts the primary key,
sets it as the foreign key, and saves the associate object.

在我的情况下,分配用户obj似乎没有提取主键并将其设置为外键。

有人能指出我的问题吗?我错过了什么?谢谢!

修改 这是Merchant对用户的反映

Merchant.reflections[:user]

=> #<ActiveRecord::Reflection::AssociationReflection:0x007f816a8b41e0
@macro=:has_one, @name=:user, @scope=nil, @options={:dependent=>:destroy},
@active_record=Merchant(id: integer, user_id: integer, company: string, 
created_at:datetime, updated_at: datetime), @plural_name="users", @collection=false, 
@class_name="User", @klass=User(id: integer, gender_id: integer, username: string,
first_name: string, last_name: string, email: string, passwd: string, salt: binary,
active: boolean, created_at: datetime, updated_at: datetime),
@foreign_key="merchant_id", @active_record_primary_key="id">

2 个答案:

答案 0 :(得分:0)

belongs_to关联需要属性<model>_idmerchant_id模型中没有User属性。

  1. 您运行rake db:migrate
  2. 是否有将merchant_id添加到users表的迁移,例如t.integer :merchant_idt.references :merchantadd_column :users, :merchant_id, :integer

答案 1 :(得分:0)

多么愚蠢的错误!我把has_one和belongs_to放在错误的文件中。我通过将has_one更改为belongs_to来实现它,反之亦然。 ;)

相关问题