【问题标题】:Creating forms for polymorphic associations in Rails在 Rails 中为多态关联创建表单
【发布时间】:2010-09-20 03:45:51
【问题描述】:

我有几个可以有 cmets 的类:

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).cmets 返回一个空数组。)

【问题讨论】:

    标签: ruby-on-rails polymorphic-associations


    【解决方案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.
    

    【讨论】:

    • 如何建立一个表单来输入评论?我不认为我想要“form_for @movie.cmets.create do |f| f.text_field :text; f.submit end”,因为我只想在实际提交时创建评论。出于某种原因,@movie.cmets.build 似乎没有将评论与电影相关联。
    • 您可以在电影放映页面上添加一个“添加评论”按钮,该按钮会将您重定向到添加了 cmets 字段的电影编辑页面。这可以如下完成:

    【解决方案2】:

    您将不得不比“......但这也不起作用”更具描述性,但总体思路是:

    @movie.comments.create( :text => params[:movie][:comment][:text] )
    

    更典型的是:

    @movie.comments.create( params[:comment] ) # or params[:movie][:comment]
    

    重要的是你首先找到@movie并通过它创建你的关联对象。这样您就不必担心Commentable 或类型或其他任何事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多