将名称与string interpolation: 连接起来:
= link_to "#{@post.user.fname} #{@post.user.lname}", user_path(@post.user_id)
有一个更好的解决方案,在用户模型中添加一个返回全名的方法。
#app/models/user.rb
def full_name
"#{fname} #{lname}"
end
并在link_to 助手中使用它:
= link_to @post.user.full_name, user_path(@post.user_id)
还有一种解决方法,使用delegate方法,这里是一个例子:
#app/models/post.rb
# Obviously post belongs to user
belongs_to :user
delegate :full_name, to: :user
# which means if the `full_name` method
# invokes on the @post model `delegate` it to user
用法:
= link_to @post.full_name, user_path(@post.user_id)
这是 Rails 魔法的另一个例子:
= link_to @post.full_name, @post.user
如您所见,我省略了 user_path 助手,只传递了一个 @post.user 对象,Rails 能够在后台为我构建路径助手。