2015-10-07 27 views
0

我有一个印象,link_to_if应与此代码的工作没有任何问题:有条件的link_to_if name参数总是被评估?

<%= link_to_if locker.student, locker.student.fullname, locker.student do %> 
    <div>more complicated</div> 
<% end %> 

我得到的“全名”无方法错误。 所以,我的印象是,当学生存在时,链接将被创建,否则块会被渲染。

但是,无论if条件如何,似乎名称参数总是被执行,所以当没有学生放在储物柜上时,它就会中断。 这是真的吗?

如果是(奇怪),我该如何做这样的事情?我想要的是避免一个标准的if.else。

Thx

回答

1

是它始终执行:它是函数的一个参数。

你可以这样做:

<%= link_to_if locker.student, locker.student.try(:fullname), locker.student do %> 
    <div>more complicated</div> 
<% end %> 

或者使用标准if包裹link_to

优雅的方式来避免这些问题都是空的对象和/或装饰

+0

没想到试试,但是,因为我尝试链接也有不好的经验:),但它的确有窍门。谢谢!! –

+0

耶'尝试'是方便的,但不是那么好:它基本上是一个变相的'救援零'。 – apneadiving