0

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

商家模式

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

我创建一个用户 obj 并将其保存到数据库没有问题。g将 Gender obj 分配给 User 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商家 objm

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

正如has_oneRail 的 API 中的方法中所述

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

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

谁能指出我的问题?我错过了什么?谢谢!

编辑 这里是商家对用户的反映

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">
4

2 回答 2

0

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

于 2013-11-13T07:38:17.760 回答
0

belongs_to关联需要一个属性<model>_id。模型中没有merchant_id属性User

  1. 你跑了rake db:migrate吗?
  2. 是否存在添加merchant_idusers表中的迁移,例如t.integer :merchant_idort.references :merchantadd_column :users, :merchant_id, :integer
于 2013-11-13T00:40:39.873 回答