Rails:查找分配给一个 Y 的所有 X
我是 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 method
find_all_by_experiment_id' for #`
What can I use to get the users that are assigned to the current experiment?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为 Experiment.find(params[:experiment_id]).users 应该可以工作。
I think Experiment.find(params[:experiment_id]).users should work.
首先,您应该在实验模型中定义它有更多用户。我猜实验和用户之间存在 1 对 n 或 n 对 n 的关系。看起来像这样:
然后,当您通过调用
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:
Then when you look up the Experiment in the experiment's controller by calling
Experiment.find(params[:experiment_id])
, you can call itsusers
method to get the list of users related to the experiment.