Ruby Enumerable Collect Array still showing at end of list [duplicate]

半城伤御伤魂 提交于 2019-12-11 02:39:57

问题


I'm using Ruby enumerable to create an array of from another model. The method "companiesattending"

class Conference < ActiveRecord::Base
  has_many :accountconferences
  has_many :accounts, :through => :accountconferences
  accepts_nested_attributes_for :accounts

  def companiesattending
    accounts.collect {|f| f.name }
  end

end

What's strange is when I put this into a view I get a list of items as expected and then some of of the members of the array at the end of the list still in an array:

The View Results

    <ul style="list-style-type: none;">
        <li>Company 1</li>
    </ul>

    <ul style="list-style-type: none;">
        <li>Company 2</li>
    </ul>
[&quot;3point5.com&quot;, &quot;Company&quot;, &quot;5.1&quot;, &quot;A O Coolers&quot;, &quot;Abo Gear&quot;, &quot;Access Fund&quot;, &quot;AceCamp.com&quot;, &quot;ACORN&quot;

/app/views/conferences/_accounts.html.erb

<div class="span5">
<h3 class="pull-left">Companies That Are Attending</h3></br></br></br>
 <%= @accounts.each do |f|%>
    <ul style="list-style-type: none;">
        <li><%= f %></li>
    </ul>
 <% end %>
</div>

/app/models/conferences.rb (Show Action)

  def show
    @conference = Conference.find(params[:id])
    @accounts = @conference.companiesattending  
  end

What am I missing?


回答1:


Instead of:

<%= @accounts.each do |f|%>

Use this without =:

<% @accounts.each do |f|%>

= is the reason your code is displaying the array.




回答2:


each returns self, i.e. the object it was called on, and <%= displays whatever the expression inside of it evaluates to. The expression inside of <%= is @accounts.each which returns @accounts, ergo, @accounts is displayed.

If you don't want the array displayed, use <% which only executes but doesn't display code.



来源:https://stackoverflow.com/questions/16651061/ruby-enumerable-collect-array-still-showing-at-end-of-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!