[英]filter results from show action
In my Rails app I have a users_controller with an action that displays a users profile, but I would like it to only display a users profile if the user has a specific value set in the database called is_rec set to true. 在我的Rails应用程序中,我有一个users_controller,带有显示用户个人资料的操作,但是如果用户在数据库中将is_rec的特定值设置为true,则我希望它仅显示用户个人资料。
The below is my attempt but it doesn't work. 以下是我的尝试,但不起作用。 I used a scope for the index and that worked well but I wasn't able to get a scope to work when I was working with the
show action
我为索引使用了范围,但效果很好,但是在执行
show action
时无法使范围起作用
def rec_profile
@user = User.find(params[:id])
@user if @user.is_rec == 'true'
end
I could do something like this in the view but I wanted to see if there was a way to do it in the controller instead? 我可以在视图中执行类似的操作,但是我想看看是否有一种方法可以在控制器中执行?
<% if @user.rec == 'true' %>
<% show page here %>
<% end %>
You can use find_by
and pass 1 or more attributes to look for in your database. 您可以使用
find_by
并传递1个或多个属性在数据库中查找。 So you could pass the id and is_rec attributes and get your user. 因此,您可以传递id和is_rec属性并获取您的用户。
User.find_by(id: params[:id], is_rec: true)
Or you can use where to get all users where is_rec is true and then filter for the user whose id matches with params[:id]: 或者,您可以使用where来获取is_rec为true的所有用户,然后过滤其id与params [:id]匹配的用户:
User.where(is_rec: true).find(params[:id])
Which eventually can be converted to a scope for easy access: 最终可以将其转换为易于访问的范围:
scope :with_rec, -> { where(is_rec: true) }
For being used then as: 然后用作:
User.with_rec.find(params[:id])
with_rec
is just an example name as scope, you could use whatever you want. with_rec
只是作为范围的示例名称,您可以使用任何所需的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.