在Rails中创建多态关联的表单

gra*_*tur 14 ruby-on-rails polymorphic-associations

我有几个类,每个都有评论:

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
Run Code Online (Sandbox Code Playgroud)

如何为新电影评论创建表单?我补充道

resources :movies do
    resources :comments
end
Run Code Online (Sandbox Code Playgroud)

到我的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
Run Code Online (Sandbox Code Playgroud)

(其中"text"是Comment表中的一个字段)但这也不起作用.

我真的不确定如何将评论与电影联系起来.例如,

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

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

Roh*_*hit 7

由于您已在模型中创建了多态关联,因此您无需再在视图中担心这种关联.您只需要在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.
Run Code Online (Sandbox Code Playgroud)

  • 如何构建表单以输入评论?我不认为我想要"form_for @ movie.comments.create do | f | f.text_field:text; f.submit end",因为我只想创建评论,如果实际提交的话.由于某种原因,@ movie.comments.build似乎没有将评论与电影相关联. (3认同)
  • &lt;% form_for(@movie) 做 |f| %&gt; &lt;%= f.error_messages %&gt; &lt;p&gt; &lt;%= f.label :name %&gt;&lt;br /&gt; &lt;%= f.text_field :name %&gt; &lt;/p&gt; &lt;% f.fields_for :comments do | v| %&gt; &lt;p&gt; &lt;%= v.label :comment %&gt; &lt;%= v.text_area :comment %&gt; &lt;/p&gt; &lt;% end %&gt; &lt;% end %&gt; (3认同)