[英]How to nest a Rails scriptlets within each other?
I have got a few models that are different types of user account - ie a User model, an Admin model, a Guest model. 我有一些不同类型的用户帐户模型-即用户模型,管理员模型,来宾模型。
I'm trying to create a forum as part of an application I am making. 我正在尝试创建一个论坛,作为我正在制作的应用程序的一部分。 When a post is created, the user_type attribute is set to the type of user that created the post. 创建帖子后,将user_type属性设置为创建该帖子的用户的类型。 What I want to do seems to be something pretty simple, but I can't seem to work it out. 我想做的事情似乎很简单,但我似乎无法解决。 Basically, I want to get the username of the person that created the post. 基本上,我想获取创建帖子的人的用户名。 I can't just use something like post.user.username, as I have a few different models, and I don't want to have to do something ugly with if statements, so is there a better way around? 我不能仅仅使用post.user.username之类的东西,因为我有几种不同的模型,而且我不想对if语句做一些丑陋的事情,那么有没有更好的方法呢? This might show what I'm trying to achieve (although this doesn't work): 这可能显示出我正在尝试实现的目标(尽管这不起作用):
created by:<%= post.#{user_type}.username %>
which would then output to the relevant code: 然后将其输出到相关代码:
post.user.username
or post.admin.username
or post.guest.username
Thanks! 谢谢!
Maybe your best course of action 也许是您最好的选择
class Post < ActiveRecord::Base
...
def username
[user,admin,guest].find(&:present?).try(:username)
end
end
You can stick this in your model, or even better, a decorator . 您可以将其粘贴到模型中,或者甚至可以粘贴到装饰器中 。
Now you can just do this in your view: 现在,您可以在自己的视图中执行此操作:
created by:<%= post.username %>
find
retrieves the first thing that responds to present?
find
检索响应的第一件事present?
. 。 In other words, it finds the first thing that is not nil. 换句话说,它找到的第一件事不是零。 Then, we try to call username
on whatever that method returns. 然后,我们尝试在该方法返回的任何值上调用username
。 If there is no user
, admin
, or guest
for this post, the method will return nil
. 如果此帖子没有user
, admin
或guest
,则该方法将返回nil
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.