Ruby-on-rails 检查属性是否存在并设置的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19212140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:49:51  来源:igfitidea点击:

What is the best way to check if an attribute exists and is set?

ruby-on-railsrubyhaml

提问by Eric Norcross

I have a common view that lists two different models. The only difference is that when setting the link_toaction, one of the models has a linkattribute and the other doesn't. I want to check if the linkattribute exists, and if it does, check if it's set. I have the following which works, but I was wondering if there was a better way.

我有一个共同的观点,其中列出了两种不同的模型。唯一的区别是在设置link_to动作时,一个模型有一个link属性,另一个没有。我想检查该link属性是否存在,如果存在,请检查它是否已设置。我有以下工作,但我想知道是否有更好的方法。

%li
  - if @element.has_attribute?("link") && @element.link
    = link_to @element.title, @element.link
  - else
    = link_to @element.title, @element

回答by ck3g

You could use presence:

你可以使用presence

= link_to @element.title, (@element.link.presence || @element)

Or, if @elementmight not have linkat all, you could use try:

或者,如果@element可能根本没有link,您可以使用try

= link_to @element.title, (@element.try(:link) || @element)

回答by ahnbizcad

I believe you can just do @element.attribute?(e.g. @element.link?) (I suppose we could call it "magic attributes".)

我相信你可以做@element.attribute?(例如@element.link?)(我想我们可以称之为“魔法属性”。)

This checks for

这检查

  • the attribute existing on the model
  • the value not being nil
  • 模型上存在的属性
  • 值不为零

Exactly what you want.

正是你想要的。

回答by OneChillDude

Try using the attributes hash. This hash will return a key => valuemapping of all of an activerecord object's attributes.

尝试使用属性哈希。这个散列将返回一个活动记录key => value对象的所有属性的映射。

if @element.attributes['link']
  # Here we are
else
  # default
end