【问题标题】:Rails: Determine Which Model an Object is Derived FromRails:确定对象源自哪个模型
【发布时间】:2012-07-16 18:34:30
【问题描述】:

我有一个包含来自两个模型的对象的数组:

  @search_results = User.find(:all, :conditions => ['name LIKE ?', "%#{params[:query]}%"])
  @search_results += Book.find(:all, :conditions => ['title LIKE ?', "%#{params[:query]}%"])

然后我尝试像这样解析它们:

<% @search_results.each do |result| %>
  <% if result.title %>
    <%= link_to result.title, result %>
  <% else %>
    <%= link_to result.name, result %>
  <% end %>
<% end %>

我曾希望 if 语句能够解析来自用户(没有)的书籍(有标题)。不幸的是,if 语句本身会抛出错误“Undefined method `title' for #”。我还能做些什么来确定对象所属的模型?

PS。我想将两个模型保留在同一个数组中,以便可以通过共享属性 page_views 对结果进行排名。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    你想要

    result.class.name
    

    参考:How do I get the name of a Ruby class?

    【讨论】:

      猜你喜欢
      • 2015-01-29
      • 1970-01-01
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多