如何为以下代码创建或声明

时间:2016-08-02 15:54:07

标签: ruby-on-rails

我希望能够显示一个刻度或X,具体取决于广告系列是批准还是拒绝。目前我可以一次做一个但是如何组合或添加或声明呢?我所做的每一次尝试都以失败告终。

%td= campaign.status == "Approved" ?  '<span class="glyphicon glyphicon-ok text-success"></span>'.html_safe : campaign.status

我认为这样可行,但遗憾的是没有:

%td= campaign.status == "Approved" ?  '<span class="glyphicon glyphicon-ok text-success"></span>'.html_safe || campaign.status == "Rejected" ? '<span class="glyphicon glyphicon-remove text-success"></span>'.html_safe 

1 个答案:

答案 0 :(得分:1)

使用三元时,您没有or选项,只能使用?:

要小心,因为嵌套三元操作会导致代码严重混乱,我认为没有任何优势

您应该使用||,而不是使用:,这意味着elsetry it here

为了清晰起见,我将在代码中打破代码:

%td=
campaign.status == "Approved"
? '<span class="glyphicon glyphicon-ok text-success"></span>'.html_safe
: campaign.status == "Rejected"
? '<span class="glyphicon glyphicon-remove text-success"></span>'.html_safe
: '<span class="SOME-ICON-TO-SHOW-UNEXPECTED-STATUS"></span>'.html_safe

此代码与此相同:

if campaign.status == "Approved"
  '<span class="glyphicon glyphicon-ok text-success"></span>'.html_safe
elsif campaign.status == "Rejected"
  '<span class="glyphicon glyphicon-remove text-success"></span>'.html_safe
else
  '<span class="SOME-ICON-TO-SHOW-UNEXPECTED-STATUS"></span>'.html_safe
end

我建议您为此目的使用视图帮助程序,这将使您的代码更清晰:

%td=campaign_status(compaign.status)