【问题标题】:Ruby convert expanded if statement into one-linerRuby将扩展的if语句转换为单行
【发布时间】:2023-03-13 16:25:01
【问题描述】:

鉴于这两个部分之间只有微小的差异,有没有更好的方法来编写这个 if/else 语句?

if current_admin_user.role?(:admin)
  f.input :invoice_file_date, as: :datepicker if f.object.invoice_file.present?
else
  f.input :invoice_file_date, as: :datepicker, :input_html => { :disabled => true } if f.object.invoice_file.present?
end

【问题讨论】:

    标签: ruby-on-rails ruby if-statement syntactic-sugar


    【解决方案1】:

    我不记得:disabled => false 是否会做你想做的事,或者这是“只检查属性是否存在而不是值”的那些之一,但这会起作用。但不确定它是否更好。

    f.input :invoice_file_date, as: :datepicker, 
            :input_html => { :disabled => !current_admin_user.role?(:admin) } if f.object.invoice_file.present?
    

    【讨论】:

    • 这是一个非常巧妙的解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2023-04-08
    • 2014-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多