16

それぞれにコメントを付けることができるクラスがいくつかあります。

class Movie < ActiveRecord::Base
    has_many :comments, :as => :commentable
end

class Actor < ActiveRecord::Base
    has_many :comments, :as => :commentable
end

class Comment < ActiveRecord::Base
    belongs_to :commentable, :polymorphic => true
end

新しい映画コメントのフォームを作成するにはどうすればよいですか? 追加した

resources :movies do
    resources :comments
end

私のroutes.rbに、そしてnew_movie_comment_path(@movie)を試してみましたが、これによりcommentable_idとcommentable_typeを含むフォームが得られます[ユーザーが直接入力するのではなく、自動的に入力したい]。私も自分でフォームを作成してみました:

form_for [@movie, Comment.new] do |f|
    f.text_field :text
    f.submit
end

(「テキスト」はコメントテーブルのフィールドです)しかし、これも機能しません。

コメントを映画に関連付ける方法がまったくわかりません。例えば、

c = Comment.create(:text => "This is a comment.", :commentable_id => 1, :commentable_type => "movie") 

ID 1 のムービーに関連付けられたコメントを作成していないようです (Movie.find(1).comments は空の配列を返します)。

4

2 に答える 2

7

モデルでポリモーフィックな関連付けを作成したので、ビューでそれについて心配する必要はもうありません。コメント コントローラーでこれを行うだけです。

@movie = Movie.find(id) # Find the movie with which you want to associate the comment
@comment = @movie.comments.create(:text => "This is a comment") # you can also use build
# instead of create like @comment = @movie.comments.create(:text => "This is a comment")
# and then @comment.save
# The above line will build your new comment through the movie which you will be having in
# @movie.
# Also this line will automatically save fill the commentable_id as the id of movie and 
# the commentable_type as Movie.
于 2010-09-20T05:09:46.420 に答える
3

「...しかし、これも機能しません」よりも説明的である必要がありますが、一般的な考え方は次のとおりです。

@movie.comments.create( :text => params[:movie][:comment][:text] )

より典型的には:

@movie.comments.create( params[:comment] ) # or params[:movie][:comment]

重要なことは、最初に見つけ@movieて、それを介して関連オブジェクトを作成することです。Commentableそうすれば、タイプや何かについて心配する必要はありません。

于 2010-09-20T04:45:50.780 に答える