2016-08-01 48 views
1

我试图通过我的控制器获取值,并且它在我的日志中正确打印。但是,当我在我的视图中打印时发生错误。Ruby on Rails - 值在日志中正确打印但未在视图中

控制器:

@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> 

错误: 在控制器记录它提供了正确的类别(如桌子,虚拟化,私有)每个潜在客户的价值,但在视图中,它为每个潜在客户提供最后一个潜在客户的分类价值。

+0

什么是错误? –

+0

没有错误,它只是给出了第一个潜在客户属性类别的值。 “虚拟”..相反,它应该给出它所关注的行的类别。我会在问题中添加更新。 –

+0

很难看到错误在哪里。试着描述你想要什么以及你在答案中实际得到了什么。也许可以在代码中添加注释以显示它在做什么。 –

回答

1

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

因此,例如,如果循环运行的类别的第一时间是“桌子”的@category_names变得它将覆盖@category_name变量“书桌”

然而它运行的类别的第二时间变成“虚拟”。

您需要的category_names推到一个哈希与铅

@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 

很假的ID,但应该帮助你

然后在视图中做

@category_names [铅.id.to_s] .to_sentence

+0

太棒了,它几乎可以工作。不幸的是,现在只有to_sentence不再工作了。我猜是因为.to_s? –

+0

我得到的错误是:未定义的方法'to_sentence'为零:NilClass –

+0

永远不要介意。我修好了它。必须在我的控制器的else部分添加@category_names [k.id.to_s] = [“”]。 –