ruby-on-rails - 我如何处理 View 中的 nils?

标签 ruby-on-rails ruby

我设置了以下模型:

class Contact < ActiveRecord::Base
  belongs_to :band
  belongs_to :mode

  validates_presence_of :call, :mode
  validates_associated :mode, :band
  validates_presence_of :band, :if => :no_freq?
  validates_presence_of :freq, :if => :no_band?

protected

  def no_freq?
    freq.nil?
  end

  def no_band?
    band.nil?
  end
end

class Band < ActiveRecord::Base
  has_many :logs
end

class Mode < ActiveRecord::Base
  has_many :logs
end

当我在我的 View 中输入频率时,如果输入了频率,则不允许指定波段。这在我的其他观点中造成了问题,因为 band 现在为零。我如何允许不指定 band 并在我的 indexshow View 中显示为空,然后在 edit View 中允许在以后指定一个。

通过执行以下操作,我已经能够让我的索引显示空白:

contact.band && contact.band.name

但我不确定这是否是最佳方法,而且我不确定如何将类似的解决方案应用于我的其他观点。

非常感谢 Rails 新手!

最佳答案

在我看来,我将以下内容用于我的 View 中可能为 nil 的对象:

<%= @contact.band.name unless @contact.band.blank? %>

如果你的对象是一个数组或者散列,你可以使用empty?函数代替。

<%= unless @contacts.empty? %>
 ..some code
<% end %>

希望这对您有所帮助!

D

关于ruby-on-rails - 我如何处理 View 中的 nils?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601036/

相关文章:

ruby-on-rails - 在 rails 中单击带有 cucumber 的 facebook 连接按钮

ruby-on-rails - 如何在配置文件中使用Rails.root?

ruby-on-rails - 在启用事务夹具的 Rails 4 中测试 after_commit 钩子(Hook)

html - 在 html.erb 文件中创建方法

css - 字体在 Rails 4 中不生效

ruby-on-rails - Emacs 做 ruby​​ on rails 有哪些有用的包?

ruby-on-rails - 如何在 Heroku 中查看详细日志,类似于我在开发环境中看到的日志?

ruby-on-rails - 如何使用 Ruby MiniTest::Spec 和 Rails 进行 API 集成测试?

ruby-on-rails - 如何在 Ruby 中将时间整数转换为日期?

ruby - 字符串的 map() 的 Ruby 等价物是什么?