Rails的HAS_ONE与类名和外键 [英] Rails has_one with class name and foreign key

查看:369
本文介绍了Rails的HAS_ONE与类名和外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Rails的模式,我用两个 HAS_ONE 关系:请求朋友。当在控制台中使用:

  F = FriendRequest.all
F [0] .requester
 

我得到的ActiveRecord :: StatementInvalid:SQLite3的::的SQLException:没有这样的列:users.requester_id:选择用户*从用户WHERE用户,requester_id= 4限制。 1

我真的不知道如何指定一个类名和密钥,指定备案`HAS_ONE的关系。这是我的模型:

 类FriendRequest<的ActiveRecord :: Base的
  HAS_ONE:请求者:将class_name => 用户,:foreign_key => requester_id
  HAS_ONE:朋友:将class_name => 用户,:foreign_key => friend_id
结束
 

我怎么能这样做呢?在 belongs_to的关系,我用的是相同的,显然是将 HAS_ONE belongs_to的。谢谢!

解决方案

  HAS_ONE:请求者:将class_name => 用户,:foreign_key => requester_id
 

该行(从您发布的code)表示请求用户,和表用户应包含一列 requester_id 是对 friend_requests 记录。铁轨错误消息指出该列 requester_id 不存在(你必须通过的迁移)。

在这种情况下,使用

 导轨产生迁移AddRequesterIdToUsers requester_id:整数
 

这将产生迁移:

 类AddRequesterIdToUsers< ActiveRecord的::迁移
  高清变化
    add_column:用户:requester_id,整数
  结束
结束
 

和运行他们迁移耙分贝:迁移

看href="http://guides.rubyonrails.org/association_basics.html"> Rails的关系指南上的 HAS_ONE belongs_to的,以及如何使用它们。

I have a Rails model which I use two has_one relations: requesterand friend. When in the console I use:

f = FriendRequest.all
f[0].requester

I get ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: users.requester_id: SELECT "users".* FROM "users" WHERE "users"."requester_id" = 4 LIMIT 1 .

I don't really know how to specify a `has_one' relationship with a class name and a key which specifies the record. This is my model:

class FriendRequest < ActiveRecord::Base
  has_one :requester, :class_name => "User", :foreign_key => "requester_id"
  has_one :friend, :class_name => "User", :foreign_key => "friend_id"
end

How could I do it? In a belongs_to relationship I use the same, obviously replacing has_onewith belongs_to. Thanks!

解决方案

has_one :requester, :class_name => "User", :foreign_key => "requester_id"

This line (from the code that you posted) indicates that the requester is a User, and the table users should contain a column requester_id that is the foreign key toward friend_requests records. The rails error message states that the column requester_id does not exists (you have to create it via a migration).

In this case, use

rails generate migration AddRequesterIdToUsers requester_id:integer

It will generate the migration:

class AddRequesterIdToUsers < ActiveRecord::Migration
  def change
    add_column :users, :requester_id, :integer
  end
end  

And run them migration with rake db:migrate.

Look at the Rails Relation Guide for more information on differences between has_one and belongs_to, and how to use them.

这篇关于Rails的HAS_ONE与类名和外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆