Ich erstelle eine meiner ersten RoR-Anwendungen - ein Forum. Ich versuche, dem Forum Kommentare hinzuzufügen, aber ich bekomme einige Fehler. Ich habe für ähnliche Probleme gegoogelt, aber keine scheint mein Problem zu lösen. Hier ist mein Code:Ruby on rails - Kommentare können nicht erstellt werden. NoMethodError
Kommentare Controller:.
class CommentsController < ApplicationController
def create
@forum = Forum.find(params[:forum_id])
if [email protected]?
puts "Forum object is not nil"
end
@comment = @forum.comment.create(comment_params)
redirect_to forum_path
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
Das Forum Controller automatisch generiert wird, und ich habe nicht verändert (erzeugt Schienen erzeugen Gerüst Forum verwenden, wenn Sie es immer noch sehen wollen, lassen Sie ich weiß)
class Comment < ApplicationRecord
belongs_to :forum
end
class Forum < ApplicationRecord
has_many :comments
validates :title, presence: true,
length: {maximum: 50}
validates :body, presence: true
end
die folgende Formular aus dem show.html.erb für Abschnitt ist für das Forum, um
<h2>Comments</h2>
<% @forum.comments.each do |comment| %>
<p>
<%= comment.body %>
</p>
<% end %>
<h2>Add a comment</h2>
<%= form_for([@forum, @forum.comments.build]) do |f| %>
<p>
<%= f.label :body %><br/>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Und das ist der Fehler von Schienen:
undefined method `comment' for #<Forum:0x444d518>
mit dem folgenden Auszug:
end
@comment = @forum.comment.create(comment_params) #highlighted
redirect_to forum_path
end
1) Rails 3-Wege veraltet ist. 2) Bitte formatieren Sie Ihren Beitrag. – coreyward
Ich stimme mit coreward überein, Wenn dies eine neue App ist, würde ich Rails 5 empfehlen. Wenn Sie eine etwas ältere Version möchten, verwenden Sie die neuesten Rails 4. Übrigens, die Tatsache, dass Ihre Modellklasse von 'ApplicationRecord' erbt zu glauben, dass Sie Rails 5 verwenden. –