Rails的belongs_to的关联(含:将class_name)返回nil [英] Rails belongs_to association (with :class_name) returns nil

查看:261
本文介绍了Rails的belongs_to的关联(含:将class_name)返回nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是比较新的Rails开发,我有一个小团体问题。我想的名字比它链接到模型中的不同关联的东西。

I'm relatively new to Rails development and I'm having a minor associations problem. I'd like to name an association something different than the model it's linked to.

我有以下2种型号:

class User < ActiveRecord::Base
  has_many :events
end

class Event < ActiveRecord::Base
  belongs_to :admin, :class_name => "User" # So we can call event.admin to retrieve the User who owns this Event
end

我建一个用户,如下所示:

I build a User as follows:

event = event.create! :title => "New Event"

user = User.create! :username => "thinkswan"
user.events << event
user.save

当我跳进我收到以下控制台:

When I hop into the console I receive the following:

irb> user = User.find(1)
irb> user.events
=> [#<Event id: 1, title: "New Event", user_id: 1, created_at: "2011-06-09 06:41:09", updated_at: "2011-06-09 06:41:10">]

irb> event = Event.find(1)
irb> event.user_id
=> 1
irb> event.admin
=> nil

任何人都可以解释为什么管理​​的关联没有返回用户它的指向?谢谢!

Can anyone explain why the admin association isn't returning the User it's pointing to? Thanks!

推荐答案

您需要同时指定:将class_name :foreign_key ,例如:

You need to specify both :class_name and :foreign_key, for example:

belongs_to :admin, :class_name => "User", :foreign_key => "user_id"

这篇关于Rails的belongs_to的关联(含:将class_name)返回nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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