简体   繁体   English

在rails的activeRecord关系ruby中搜索

[英]Search within activeRecord relation ruby on rails

This is my controller code 这是我的控制器代码

@users = User.all

Inside view I have a drop-down from which I select a user. 内部视图中,我有一个下拉菜单可供选择。 I want to show details of that users before submitting. 我想在提交之前显示该用户的详细信息。 For that I need that users details. 为此,我需要用户详细信息。 I don't want to go to database again. 我不想再去数据库。 So how do I search in @users object for that user's details. 因此,如何在@users对象中搜索该用户的详细信息。 Which one is faster and more efficient searching in already loaded object or sending a ajax request for that record ? 在已加载的对象中搜索或为该记录发送ajax请求,哪个更快,更有效?

in your controller you do 在您的控制器中

def index
   @users = user.all
end

instance variables from your controller action are available in the view 视图中提供了控制器操作的实例变量

<% @users.each do |user| %>
   <%= @user.name %>
<% end %>

If you want to display also association, in your controller index action use 如果您还想显示关联,请在控制器索引操作中使用

@users = User.includes(:your_association)

You can do it in different ways. 您可以用不同的方式来做。
1. We can write ajax call according to user and display data by ajax. 1.我们可以根据用户编写一个ajax调用,并通过ajax显示数据。
2. Make content in the same page and show or hide them according to user 2.在同一页面中制作内容,并根据用户显示或隐藏它们

Way 2 is least preferred way put the details in the same page and us js to display its content. 方式2是最不推荐的方式,将详细信息放在同一页中,并使用js显示其内容。 For eg. 例如。 we have user with id=2 and you want to see all the details of this user then withing loop of user make details of all user and hide them 我们有一个id = 2的用户,您想查看该用户的所有详细信息,然后在用户循环的情况下,为所有用户创建详细信息并将其隐藏

<div id='user-1' class='hidden'> all details of user 1</div>
<div id='user-2' class='hidden'> all details of user 2</div>
<div id='user-3' class='hidden'> all details of user 3</div>

Write a simple Jquery or JavaScript which will remove hidden class according to your selected user and user will be able to see details of those user which they want to see (don't forget to hide all other user information). 编写一个简单的Jquery或JavaScript,它将根据您选择的用户删除隐藏的类,并且用户将能够看到他们想要看到的那些用户的详细信息(不要忘记隐藏所有其他用户信息)。 It will increase the page size and we have lot of those data which we do not want to show. 它将增加页面大小,并且我们有很多我们不想显示的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM