简体   繁体   中英

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. 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? 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? . In other words, it finds the first thing that is not nil. Then, we try to call username on whatever that method returns. If there is no user , admin , or guest for this post, the method will return nil .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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