2015-01-02 28 views
0

我想了解我有一些我的Rails項目中遇到的問題。我有兩個型號,嵌套模型尺寸較大(+1),比過去在Rails的

第一招:

class Donkey < ActiveRecord::Base 
    has_many :comments, dependent: :destroy 

    validates :name, :surname, :age, presence: true 
end 

第二個:

class Comment < ActiveRecord::Base 
    belongs_to :donkey 

    validates :comment, :commenter, presence: true 
end 

我的問題是我之前添加一條記錄評論模式,@ donkey.comments.size爲1並且返回的對象是零。

要從此逃避我使用,

<% @donkey.comments.each do |comment| %> 
    <p><strong><%= comment.commenter %></strong></p> 
    <p><%= comment.comment %></p> 

    <% if comment.id.present? %> 

    <p><%= link_to 'Destroy Comment', donkey_comment_path(@donkey, comment), 
       method: :delete, data: { confirm: 'Do you really want to delete this question?' } %></p> 

    <% end %> 

<% end %> 

上面的代碼我的視圖文件,如果你留意,你可以看到我使用if語句沒有得到一個錯誤。 (零對象)

我的 '添加註釋' 從視圖文件在下面的代碼,

<%= form_for([@donkey, @comment]) do |f| %> 
    <p><%= f.label :commenter %>: <%= f.text_field :commenter %></p> 
    <p><%= f.label :comment %>: <%= f.text_area :comment %></p> 
    <%= f.submit %> 
<% end %> 

而且@comment = @ donkey.comments.build在我的控制器。

我想了解這個錯誤,這就是爲什麼我做了這樣一個簡單的模型。我正在檢查SQL服務器中沒有記錄,但@ donkey.comments.size爲1且沒有對象。

任何人都可以幫助我在這個問題上?

非常感謝您的寶貴時間,

+0

您是否嘗試過創建驢在控制檯中留言以隔離問題是否存在於模型中? – lcguida

+0

感謝您的回覆@rockskull。我銷燬了開發數據庫並再次遷移並登錄到rails控制檯,並從那裏創建了Donkey和Comment記錄=>結果是有一條記錄,但大小爲2.模型中存在什麼問題?這很簡單,你可以看到上面..真的很好奇:( – manorie

回答

0

你會build在你的控制器評論的原因是這樣你就可以訪問它在你看來,它然後與上提交的形式發送。

如果您在視圖中使用form.fields_for來訪問您試圖以該窗體創建的主對象的關係,則這是一種常見模式。在你的情況@donkey將是你的主要對象,你會得到訪問一個comment在您看來,您可以遍歷@donkey.comments,你總是會得到至少一個顯示。

的問題是,您要添加到您的@donkey.comments列表非持久性註釋,它目前還沒有一個id所以,當你提到在這裏

donkey_comment_path(@donkey, comment)

一切爆炸。

所以,你正在做正確的事情在檢查其是否具有和身份證先到這裏

<% if comment.id.present? %>

,但更多的「Rails的路」將是要麼

<% if comment.persisted? %>

<% unless comment.new_record? %>

通知unless上述

看到這裏的API這個東西http://api.rubyonrails.org/classes/ActiveRecord/Persistence.html#method-i-persisted-3F

希望這不會使它變得更加複雜;)

+0

非常感謝您的解釋,我發現最後的錯誤,但我認爲在控制器中創建一個新的空註釋不能與以前記錄的對象混合在一起感謝分享Rails的方式與我:) – manorie

0

開放軌控制檯,並嘗試這一點,並找到什麼是對

> @donkey = Donkey.find(1) 
> @donkey.comments 
> @donkey.comments.inspect 
> @donkey.comments.size 
+0

感謝您的評論。Rails控制檯給出,irb(main):004:0> @ donkey.comments.size => 0但在視圖中它仍然顯示大小爲1 ,如此奇怪:( – manorie

+0

好吧,你使用任何調試工具/寶石即pry-rails,pry-byebug? 或RubyMine的調試工具? 如果是的話,你可以使用binding.pry(放置中斷點),看看是什麼去那裏 – illusionist

0

去它就是這麼奇怪,

當我刪除

@comment = @donkey.comments.build 

from DonkeyController and change <%= form_for from([@keykey,@c omment])do | f | %>到,

form_for([@donkey, @donkey.comments.build]) do |f| 

錯誤消失。

你覺得我需要打開這個錯誤機票還是我做錯了什麼,宣佈內部控制@comment。