简体   繁体   English

Rails if语句形式为simple_form和HAML

[英]Rails if statement in form with simple_form and HAML

I have the following code in form that automatically puts the position of the object into input, using the if statement to eliminate this from happening when user edits. 我有以下形式的代码,该代码会自动使用if语句消除对象在用户编辑时发生的情况,从而将对象的位置自动输入到输入中。

- if @collection_page.new_record?
  = f.input :position, :label => "Display order:", input_html: { value: Spree::CollectionPage.last.position + 1 }
- else
  = f.input :position, :label => "Display order:"

I'm having trouble when there are no records and creating the first one, I get the usual nil class error. 当没有记录并创建第一个记录时,我遇到了麻烦,我得到了通常的nil类错误。

undefined method `position' for nil:NilClass

Which makes sense because I don't have any records yet. 这很有意义,因为我还没有任何记录。

So just need to put a little more logic in there. 因此,只需在其中添加一些逻辑即可。

I tried: 我试过了:

- if @collection_page.new_record? || Spree::CollectionPage.last.position.present? # and @collection_page.last.position.present?

Without success 没有成功

Looking for a clean way to achieve this, thank you in advance for your help! 寻找一种干净的方法来实现这一目标,在此先感谢您的帮助!

You used an or statement. 您使用了or语句。 || is or, while && is and. 是or,而&&是and。 Also, you're checking if last.position.present? 另外,您正在检查last.position.present? which will not work if last is not present. 如果不存在last ,它将不起作用。

Try if @collection_page.new_record? && Spree::CollectionPage.last.present? 尝试if @collection_page.new_record? && Spree::CollectionPage.last.present? if @collection_page.new_record? && Spree::CollectionPage.last.present?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM