我試圖插入一個對象到數組中,而不是插入到數組中,而是在屏幕上打印內存地址。將對象添加到數組?
我有下面的代碼在我的控制器:
@article = Article.new("test","test1")
@articles << @article #this line causes the prints
而且我認爲有這樣的代碼:
<%=
@articles.each do |a|
a.titulo + "/" + a.texto
end
%>
我試圖插入一個對象到數組中,而不是插入到數組中,而是在屏幕上打印內存地址。將對象添加到數組?
我有下面的代碼在我的控制器:
@article = Article.new("test","test1")
@articles << @article #this line causes the prints
而且我認爲有這樣的代碼:
<%=
@articles.each do |a|
a.titulo + "/" + a.texto
end
%>
你的問題是你如何渲染@articles
:
<%= @articles.each do |a| a.titulo + "/" + a.texto end %>
的each
返回值是陣列本身。你想渲染數組中的每個元素,所以你應該這樣做:
<% @articles.each do |a| %>
<%= a.titulo + "/" + a.texto %>
<% end %>
這可能是預期的行爲。如果@articles
確實是一個數組,這應該工作。只需在追加後檢查數組並確保新添加的元素在那裏。如果您是從控制檯執行此操作,則您看到的打印可能是控制檯行爲,而不是<<
行爲。
由於下面的評論,我改變了我的答案以反映實際問題。您正嘗試將枚舉器呈現給視圖,而不是文章。您認爲應該是這樣的:
<% @articles.each |a| %>
<%= a.titulo + "/" + a.texto %>
<% end %>
你可能會迫使@articles是這樣一個數組:
@articles ||= []
添加您@article像你已經做
'@articles || = []'這樣做絕對不會混亂。 – tadman 2014-11-20 18:28:32
好的電話。編輯答案。 – 2014-11-20 18:30:38
創建@articles
作爲Array
,然後加入<<
。
例如,
class MyController < ...
def your_method
@articles ||= []
@article = Article.new("test","test1")
@articles << @article
end
...
end
(和/或在before_
過濾器和/或...)
問題解決。謝謝! – Afaria 2014-11-20 22:17:09