ruby-on-rails – 在Rails中创建多态关联的表单

我有几个课程,每个可以有评论:
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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...