在Ruby on Rails创建其他模型时自动生成模型



我有一个名为Video的模型,它有许多状态。我想创建每一种状态并添加到@video。

在VideosController中,我有:

 def create
    @video = Video.new(params[:video])
    Kind.all.each do |f|
      @video.statuses.new(:kind =>f, :kind_id=>f.id,:comment =>"", :time_comp => nil, :completed =>false, :video_id =>@video.id)
    end
    respond_to do |format|
      if @video.save
        format.html { redirect_to @video, notice: 'Video was successfully created.' }
        format.json { render json: @video, status: :created, location: @video }
      else
        format.html { render action: "new" }
        format.json { render json: @video.errors, status: :unprocessable_entity }
      end
    end
  end

然而,这会返回一个错误,说视频无法保存,因为状态无效。唯一的验证在我的整个项目是在状态,它只是检查,有一个video_id。我很困惑为什么我得到这个错误,并感谢任何帮助!

https://github.com/ninajlu/videos

由于状态依赖于已经存在的视频,您可能希望在创建视频后创建状态。

你既可以在视频回调中做,也可以在控制器中做。比如:

def create
  @video = Video.new(params[:video])
  respond_to do |format|
    if @video.save
      Kind.all.each do |f|
        @video.statuses.create(:kind =>f, :kind_id=>f.id,:comment =>"", :time_comp => nil, :completed =>false, :video_id =>@video.id)
      end
      # respond as before

如果你走回调路线,它将是:

class Video < ActiveRecord::Base
  after_create :create_statuses
  def create_statuses
    Kind.all.each do |f|
      statuses.create(:kind =>f, :kind_id=>f.id,:comment =>"", :time_comp => nil, :completed =>false, :video_id => self.id)
    end
  end

然后你就不会在你的控制器中提到状态——你会像往常一样保存。

最后一个解决方案是使用Service对象来协调创建视频后状态的保存。更多关于RailsCast

您试图在保存@video之前创建状态,因此它没有@video。Id,因此在验证规则

下无效。

最新更新