Rails:查找分配给一个 Y 的所有 X

发布于 2024-10-04 13:22:46 字数 721 浏览 0 评论 0原文

我是 Rails 新手,所以请原谅我提出这个可能非常愚蠢的问题。

我有一个模型用户和一个模型实验,两者都通过 HABTM 关系链接。

当我想显示时,假设:/experiments/1/users,它向我显示所有用户,而不是通过实验过滤。好的,这是因为 UsersController

因此,在 UsersController 中,我定义:

# GET /users
# GET /experiment/:experiment_id/users
def index

  if (params[:experiment_id] == nil)
    @users = User.all
  else
    @users = # HOW DO I FIND THE USERS FOR THE EXP?
  end

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @users }
  end
end

我想过滤用户,但类似 ​​User.find_all_by_experiment_id 的东西不存在:未定义方法find_all_by_experiment_id' for #`

我可以使用什么来获取分配给当前实验的用户?

I'm new to rails, so please excuse me for that possibly very stupid question.

I have a model User and a model Experiment, both linked by a HABTM relationship.

When I want to display, let's say: /experiments/1/users, it shows me all usere there are, not filtered by the experiment. Okay, that's because of the UsersController.

In the UsersController, I therefore define:

# GET /users
# GET /experiment/:experiment_id/users
def index

  if (params[:experiment_id] == nil)
    @users = User.all
  else
    @users = # HOW DO I FIND THE USERS FOR THE EXP?
  end

  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @users }
  end
end

I want to filter the users, but something like User.find_all_by_experiment_id does not exist: undefined methodfind_all_by_experiment_id' for #`

What can I use to get the users that are assigned to the current experiment?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南巷近海 2024-10-11 13:22:46

我认为 Experiment.find(params[:experiment_id]).users 应该可以工作。

I think Experiment.find(params[:experiment_id]).users should work.

红颜悴 2024-10-11 13:22:46

首先,您应该在实验模型中定义它有更多用户。我猜实验和用户之间存在 1 对 n 或 n 对 n 的关系。看起来像这样:

class Expetiment < ActiveRecord::Base
  has_many :users
  ...

然后,当您通过调用 Experiment.find(params[:experiment_id]) 在实验控制器中查找实验时,您可以调用其 users 方法获取与实验相关的用户列表。

First you should define in the Experiment model that it had more Users. I guess that there is 1-to-n or n-to-n relationship between Experiment and Users. This looks something like this:

class Expetiment < ActiveRecord::Base
  has_many :users
  ...

Then when you look up the Experiment in the experiment's controller by calling Experiment.find(params[:experiment_id]), you can call its users method to get the list of users related to the experiment.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文