尝试从关联中分配多个ID时出错

时间:2014-04-10 18:27:02

标签: ruby-on-rails view controller

这里我有一个User和Subreddit之间的关联。用户可以订阅多个Subreddit,而Subreddit可以有多个用户订阅它。

我正试图将这些Subreddits中的Feed(帖子)拉到我的视图页面中,如下所示:

def home
  @subscriptions = Subscription.where(:user_id => current_user)
  @posts = Post.where(:subreddit_id => @subscriptions.subreddit_id)
end  

显然这不会起作用,因为@subscriptions是一个订阅数组。

我尝试过这样的循环:

@subscriptions.each do |s|
  @posts = Post.where(:subreddit_id => s.subreddit_id)
end

这不起作用,@ post最终成为零。
我的问题是:
如何从Subscriptions中提取subreddit_id并将其传输到我的@posts变量?

编辑:

Tables-(订阅是用户和subreddit之间的桥接表)

Subscription  
------------
id
user_id
subreddit_id

User
------------
id
username
email

Subreddit
------------
id
subname

Post
-----------
id
subreddit_id
title
url
content

1 个答案:

答案 0 :(得分:1)

对于您的家庭定义,请先检查您的user.rb(模型)类。你应该:

has_many :subscriptions

如果您有,那么def home将成为:

def home
    @subscriptions = current_user.subscriptions # active record is magical
    subscriptions = @subscriptions.map(&:subreddit_id)
    @posts = Post.where('subreddit_id in (?)', subscriptions)
end

如果你没有

def home
    @subscriptions = Subscription.where(:user_id => current_user.id) # YOU NEED THE ID!
    subscriptions = @subscriptions.map(&:subreddit_id)
    @posts = Post.where('subreddit_id in (?)', subscriptions)
end

如果你不需要@subscriptions视图,你可以将前两行合并为一个:

def home
    subscriptions = current_user.subscriptions.map(&:subreddit_id)
    @posts = Post.where('subreddit_id in (?)', subscriptions)
end