在Rails中为多态关联创建表单 [英] Creating forms for polymorphic associations in Rails

查看:95
本文介绍了在Rails中为多态关联创建表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个班级,每个班级都可以发表评论:

I have a couple classes that can each have comments:

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

如何为新的电影评论创建表单?我添加了

How do I create a form for a new movie-comment? I added

resources :movies do
    resources :comments
end

到我的routes.rb,并尝试了new_movie_comment_path(@movie),但这给了我一个包含commentable_id和commentable_type的表格[我想自动填充它们,而不是由用户直接输入].我也尝试过自己创建表单:

to my routes.rb, and tried new_movie_comment_path(@movie), but this gives me a form containing commentable_id and commentable_type [which I want to be populated automatically, not entered by the user directly]. I also tried creating the form myself:

form_for [@movie, Comment.new] do |f|
    f.text_field :text
    f.submit
end

(其中文本"是注释表中的字段) 但这也不起作用.

(where "text" is a field in the Comment table) but this doesn't work either.

我实际上不确定如何将评论与电影相关联.例如

I'm not actually sure how to associate a comment with a movie at all. For example,

c = Comment.create(:text => "This is a comment.", :commentable_id => 1, :commentable_type => "movie") 

似乎没有创建与ID为1的电影相关的评论.(Movie.find(1).comments返回一个空数组.)

doesn't seem to create a comment associated to the movie with id 1. (Movie.find(1).comments returns an empty array.)

推荐答案

在模型中创建多态关联后,您无需再在视图中担心这一点.您只需要在评论"控制器中执行此操作即可.

As you have created the polymorphic association in your model, you need not worry about that anymore in the view. You just need to do this in your Comments controller.

@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.

这篇关于在Rails中为多态关联创建表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆