加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:52:32 所属栏目:百科 来源:网络整理
导读:我有几个课程,每个可以有评论: class Movie ActiveRecord::Base has_many :comments,:as = :commentableendclass Actor ActiveRecord::Base has_many :comments,:as = :commentableendclass Comment ActiveRecord::Base belongs_to :commentable,:polymorph
我有几个课程,每个可以有评论:
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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读