我有几个课程,每个可以有评论:
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")
解决方法
当您在模型中创建了多态关联时,您不必担心该视图中的多态关联.您只需在“注释”控制器中执行此操作.
@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.
原文地址:https://www.jb51.cc/ruby/272124.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。