我有几个课程,每个可以有评论:
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返回一个空数组.)
解决方法
当您在模型中创建了多态关联时,您不必担心该视图中的多态关联.您只需在“注释”控制器中执行此操作.
@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.