2010-07-20 133 views
0

我在嘗試創建博客應用程序時遇到以下錯誤。任何想法爲什麼?Ruby on Rails中的NoMethodError


NoMethodError in Articles#show 

Showing app/views/articles/show.html.erb where line #1 raised: 

undefined method `title' for []:Array 
Extracted source (around line #1): 

1: <h2><%= @article.title %></h2> 
2: 
3: <% if @article.category %> 
4: <p class="category"> 

從我有限的瞭解它試圖告訴我,有我在「文章」的數據庫表中沒有「標題」字段,但是你可以看到從遞減下面有克利'標題'字段!

mysql> desc articles; 
+--------------+--------------+------+-----+---------+----------------+ 
| Field  | Type   | Null | Key | Default | Extra   | 
+--------------+--------------+------+-----+---------+----------------+ 
| id   | int(11)  | NO | PRI | NULL | auto_increment | 
| user_id  | int(11)  | YES |  | NULL |    | 
| title  | varchar(255) | YES |  | NULL |    | 
| synopsis  | text   | YES |  | NULL |    | 
| body   | text   | YES |  | NULL |    | 
| published | tinyint(1) | YES |  | 0  |    | 
| created_at | datetime  | YES |  | NULL |    | 
| updated_at | datetime  | YES |  | NULL |    | 
| published_at | datetime  | YES |  | NULL |    | 
| category_id | int(11)  | YES |  | 1  |    | 
+--------------+--------------+------+-----+---------+----------------+ 
10 rows in set (0.01 sec) 

幫助?!

Bernard

Ps。希望上面表格的格式能夠保留...在預覽中看起來不太好!


相關調用的控制器代碼如下。

def show 
if is_logged_in? && @logged_in_user.has_role?('Editor') 
    @article = Article.find(params[:id]) 
else 
    @article = Article.find_all_by_published(params[:id], true) 
end 
respond_to do |wants| 
    wants.html 
    wants.xml { render :xml => @article.to_xml } 
end 
end 
+1

錯誤提示您已收到整個陣列,您認爲自己有數組中的一項。也就是說,一篇文章有​​一個標題,但不是包含所有文章對象的數組。 (我沒有使用Rails,但是我記得它在處理單數和複數時有一些神奇的功能,因爲這種回憶很模糊,所以請隨時忽略它。) – Telemachus 2010-07-20 21:11:02

+0

在這種情況下,請考慮先調試一下發送到論壇:例如輸出@ article.class – Alexey 2010-07-21 00:13:07

回答

5

我想你試圖直接從數組訪問標題元素。在訪問屬性之前,您需要遍歷每個對象。

for @article in @articles do |a| 
    <h2><%= a.title %></h2>... 
end 

只需確保在你的控制器......

@articles = Article.find(:all, :conditions => '...') 

更新

你的這部分代碼返回一個集合。

@article = Article.find_all_by_published(params[:id], true) 
+0

嗯...不知道。在我的控制器中,我在Articles數組中搜索特定的ID,並使用該結果填充@articles? @article = Article.find(params [:id]) 認爲這將意味着@article將是一個元素,而不是一個數組? – mrbernz 2010-07-21 20:58:59

+0

是的。我只是在猜測。 – 2010-07-21 21:32:15

1

它看起來像你在你的控制器分配一個空陣列@article。它應該是Article的實例(如果這是您的型號名稱)。你可以粘貼你的控制器代碼嗎?

+0

相關控制器代碼如下: - def show \t if is_logged_in? ?&& @ logged_in_user.has_role( '編輯') \t \t @article = Article.find(PARAMS [:ID]) \t別的 \t \t @article = Article.find_all_by_published(PARAMS [:ID],真) \t結束 \t respond_to do | want | \t \t wants.html \t \t wants.xml {渲染:XML => @ article.to_xml} \t年底 結束 阿列克謝會喜歡上如何調試Rails代碼的指針,此刻我只是去關閉日誌文件和Web輸出!擔心絕對是一個Rails(和編程)newb ... – mrbernz 2010-07-21 20:53:44