简体   繁体   English

问题链接Rails关联

[英]Problem chaining Rails associations

I'm somewhat of a Rails beginner, and can't shake the feeling that I'm overlooking something stupid, but here goes. 我有点像是Rails的初学者,无法撼动我忽略了一些愚蠢的感觉的感觉,但是这里有。 I'm building a simple online game that allows one user to "challenge" another, and I have the following models: 我正在构建一个简单的在线游戏,允许一个用户“挑战”另一个用户,并且具有以下模型:

class User < ActiveRecord:Base
  has_one :challenge
end

class Challenge < ActiveRecord:Base
  belongs_to :user
  belongs_to :target, :class_name => 'User'
end

The database fields are what you'd expect: Challenge has a user_id and target_id , User has a username and some password-related fields. 数据库字段是您期望的: Challenge具有user_idtarget_idUser具有username和一些与密码相关的字段。

From an empty database, I create two Users (which receive IDs 1 and 2) and a single Challenge with user_id 1 and target_id 2 . 从一个空的数据库中,创建两个用户(分别接收ID 1和2)和一个具有user_id 1target_id 2 Challenge From the console, Challenge.find(1).target returns user 2, as expected. 从控制台, Challenge.find(1).target返回用户2,如预期的那样。 What's not expected is that User.find(1).challenge.target returns not user 2, but the Challenge itself! 期望的是User.find(1).challenge.target不是返回用户2,而是返回Challenge本身!

Needless to say, I'm lost here. 不用说,我在这里迷路了。 It seems like something this basic should Just Work(tm). 看起来这个基本的东西应该可以正常工作(tm)。 Any ideas? 有任何想法吗?

You're doing things wrong here. 您在这里做错了。 User has one challenge should be like : 用户面临的挑战应该是:

class User < ActiveRecord:Base
  has_one :challenge
end

class Challenge < ActiveRecord:Base
  belongs_to :user
end

Now, a challenge simply has a user_id and you can now use something like : 现在,挑战仅包含一个user_id,您现在可以使用类似以下内容:

user.challenge

to get that challenge. 应对挑战。 Then, you just have a challenger_id for the person that makes the challenge. 然后,您只需为发起挑战的人提供一个challider_id。

If you want to get a challenge based on the challenger_id, you just create a finder or scope like : 如果您想基于Challenger_id进行挑战,则只需创建一个查找程序或范围即可:

Challenge.find_by_challenger_id(..)

EDIT - SOLUTION IN MY COMMENT BELOW : 编辑-解决方案如下:

Hmm, i think that target is an association method. 嗯,我认为目标是一种关联方法。 Try changing to something like challenger and i think it will work. 尝试更改为挑战者之类的东西,我认为它将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM