轨道3:对象使用的has_many链接:通过协会 [英] Rails 3: Object chaining with has_many :through associations

查看:144
本文介绍了轨道3:对象使用的has_many链接:通过协会的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得如何在Rails的协会工作一抓,具体地,当,当不写明确的SQL code。

I'm trying to get a grasp of how to work with associations in Rails, specifically, when and when not to write explicit SQL code.

在我的申请,我有四个模型,定义如下:

In my application, I have four models, which are defined as follows:

class User < ActiveRecord::Base
    has_many :comments
    has_many :geographies
    has_many :communities, through: :geographies

class Comment < ActiveRecord::Base
    belongs_to :user

class Community < ActiveRecord::Base
    has_many :geographies
    has_many :users

class Geography < ActiveRecord::Base
    belongs_to :user
    belongs_to :community

用户可以发表评论,并通过地理表关联到一个或多个社区(地理表存储 USER_ID community_id )。

Users can post comments, and are associated to one or more communities through the geography table (the geography table stores user_id and community_id).

我有一个索引行动列出所有的意见,我想由社区进行过滤。给定一个评论的对象,我可以通过 comment.user 用户对象,但我不能链条超出了(也就是说,像评论。 user.geography(0).community 不工作)。

I have an index action listing all comments, and I would like to filter by community. Given a comment object, I can get the user object via comment.user, but I can't chain beyond that (i.e., something like comment.user.geography(0).community doesn't work).

看来这个对象链接是轨道的一个重要功能,但它的has_many工作:通过协会?鉴于我的例子,它是通过使用对象链接摆脱comment对象的社会目标,否则我就需要编写SQL来获得用户以外的任何给出的评论对象时?

It seems this object chaining is a key feature of rails, but does it work with has_many :through associations? Given my example, is it possible to get the community object from the comment object by using object chaining, or would I need to write the SQL to get anything other than the user when given the comment object?

推荐答案

由于用户与多个社区相关联的,你需要告诉你想要的社区ActiveRecord的(或原始SQL):

Since User is associated with multiple communities, you will need to tell ActiveRecord (or raw SQL) which community you want:

comment.user.communities #=> should give you all the communities

如果你不特别在意获取所有社区和只想得到任何社区

If you don't particularly care for getting all communities and just want to get any community

comment.user.communities.first #=> should give you the first community

不过,一般你会有兴趣在一个特定的社区,基于一个条件。

But, generally you will be interested in one particular community, based on a condition.

comment.user.communities.where(name: 'Europe') #=> should give you the European community.

这篇关于轨道3:对象使用的has_many链接:通过协会的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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