微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/ruby/272124.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐