Ruby on rails 条件逻辑问题-Ruby on Rails

Ruby on rails 条件逻辑问题-Ruby on Rails,ruby-on-rails,ruby,Ruby On Rails,Ruby,我对Ruby的一些条件逻辑有问题。诚然,我对Ruby的一切都是新手 此代码导致站点无法加载: <body style="background-image:url("<%= if @is_home_page.present? '/images/bg-main-power-bg.jpg' else '/images/bg-inner-power-bg.jpg' end %>"); background-repeat:repeat-x;"> 如果没有条件,CSS的加载就很

我对Ruby的一些条件逻辑有问题。诚然,我对Ruby的一切都是新手

此代码导致站点无法加载:

<body style="background-image:url("<%= if @is_home_page.present? '/images/bg-main-power-bg.jpg' else '/images/bg-inner-power-bg.jpg' end %>"); background-repeat:repeat-x;">

如果没有条件,CSS的加载就很好

我做错了什么


谢谢

对内联条件使用三元运算符

condition ? branch_a : branch_b

a == b ? "foo" : "bar"
# is the same as
if a == b
  "foo"
else
  "bar"
end
针对您的具体情况:

@is_home_page ? '/images/bg-main-power-bg.jpg' : '/images/bg-inner-power-bg.jpg'

对内联条件使用三元运算符

condition ? branch_a : branch_b

a == b ? "foo" : "bar"
# is the same as
if a == b
  "foo"
else
  "bar"
end
针对您的具体情况:

@is_home_page ? '/images/bg-main-power-bg.jpg' : '/images/bg-inner-power-bg.jpg'

你也可以考虑把它移到助手文件中。您可以将以下内容添加到

app/helpers/application\u helper.rb

def bg_path
  return '/images/bg-main-power-bg.jpg' if current_page? root_path
  '/images/bg-inner-power-bg.jpg'
end
这会使您的视图更清晰

<body style="background-image:url("<%= bg_path %>"); background-repeat:repeat-x;">


阅读:

你也可以考虑把它移到助手文件中。您可以将以下内容添加到
app/helpers/application\u helper.rb

def bg_path
  return '/images/bg-main-power-bg.jpg' if current_page? root_path
  '/images/bg-inner-power-bg.jpg'
end
这会使您的视图更清晰

<body style="background-image:url("<%= bg_path %>"); background-repeat:repeat-x;">


阅读:

您的原始代码:您可能会收到的错误可能是由于此代码段
“背景图像:url”(您的原始代码:您可能会收到的错误可能是由于此代码段
中的第二个
“背景图像:url(”变量@is_home_page将只存在于主页上,使用此项功能?或者我需要使用.present?@resonantmedia如果未设置实例变量,它将等于nil,三元数仍将工作。但这看起来确实有点代码味道。变量@is_home_page将只存在于主页上,使用此项功能r那?或者我需要使用.present?@resonantmedia吗?如果没有设置实例变量,它将等于nil,三元数仍然可以工作。不过这看起来确实有点代码味道。我的回答完全不需要
@is\u home\u页面
变量。我的回答不需要
@is\u home\u页面
变量总共