问题
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>
["3point5.com", "Company", "5.1", "A O Coolers", "Abo Gear", "Access Fund", "AceCamp.com", "ACORN"
/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