Ruby on Rails - 在日志中正确打印的值但不在视图中

时间:2016-08-01 15:25:21

标签: ruby-on-rails view controller

我试图通过我的控制器获取值,并在我的日志中正确打印。但是,当我在我的视图中打印它时会出错。

控制器:

@leads = Lead.all.order('updated_at desc')
    @leads.each do |k|
      if k.lead_propertiesproperty_id = k.lead_properties.map(&:property_id)
        properties = Property.where(:id => property_id)
        category_ids = properties.map(&:property_category_id)
        categories = PropertyCategory.where(:id => category_ids)
        @category_names = categories.map(&:name).exists?

        Rails.logger.debug("categories: #{categories.inspect}")
        Rails.logger.debug("category_names: #{@category_names.inspect}")
      else
        @properties = "No Properties"
        @locations = "No Locations"
      end
    end
    @leads_total = Lead.all.count

查看:

  <tbody>
    <% @leads.each do |lead| %>
    <tr class="<%=cycle('odd', 'even') %> location_row" id="lead_row" data-id="<%= lead.id%>">
      <td><%= lead.id %></td>
      <td><%= lead.fullname %></td>
      <td><%= lead.email %></td>
      <td><%= lead.phone %></td>
      <td><%= @category_names.to_sentence %></td>
      <td><%= select_tag :status, options_for_select(Lead.statuses.keys.to_a{|k, v| [k.humanize.capitalize, v]}, lead.status), :class => "lead_status"%></td>
      <td><%= lead.created_at.strftime("%d %b. %Y - %T")%></td>
      <td><%= link_to (fa_icon "pencil-square-o "), edit_lead_path({:id => lead.id, :first_last_name => lead.first_last_name}), :title => 'Edit Lead', :class => "action-button" %></td>
    </tr>
    <% end %>
  </tbody>

错误: 在控制器日志中,它为每个潜在客户提供正确的类别(例如,桌面,虚拟,私有)值,但在视图中,它为每个潜在客户提供最后一个潜在客户的类别值。

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话,因为@category_names是在循环中分配的。

因此,例如,如果第一次循环运行,则类别为“desk”,@ category_names变为“desk”

然而,第二次运行该类别变为“虚拟”,它会覆盖@category_name变量。

您需要将category_names推送到具有潜在客户ID的哈希值

@category_names = {}

@lead.each do |lead|
   If lead.category_name.is_what_i_want?
     @category_names[lead.id.to_s] = lead.category_names
    end
  end

非常伪,但这应该可以帮到你

然后在视图中执行

@category_names [lead.id.to_s] .to_sentence