如何获取所有相关记录?

时间:2013-04-30 05:53:47

标签: ruby-on-rails ruby-on-rails-3

Current_user有很多喜欢的社区。最喜欢的社区可以通过此获取。

@communities = current_user.get_up_voted(Community)

然后每个社区都有很多这样的主题。

社区has_many:Community_topics
  Community_topic belongs_to:社区

现在,我如何获取属于current_user最喜欢的社区的所有主题?

我试过这个

@communities = current_user.get_up_voted(Community)

@community_topics = Community_topics.where(:community_id => @communities).page(params[:page]).order("last_active_at DESC")

但是我收到了这个错误:(

NameError (uninitialized constant UsersController::Community_topics):

2 个答案:

答案 0 :(得分:0)

按照documentation的字母:

  

has_many关联表示与另一个的一对多连接   模型。你经常会在a的“另一面”找到这种关联   belongs_to association。此关联表示每个实例   该模型具有零个或多个另一个模型的实例。

确保拼写正确,子表中有parent_table_id字段,并且已声明子表belongs_to为其父表。

答案 1 :(得分:0)

如果你制作模特:

e.g. my_model.rb

它的内容应该像这样说:

class MyModel < ActiveRecord::Base

end

所以在控制器中你会称之为:

@myvariable = MyModel.where(......)

确保您的命名约定。检查它们是否正确。