0

我有一个称为视频的模型,它具有许多状态。我想创建每种类型的状态并将其添加到VideosController的def create中的@ video.statuses中。在Ruby on Rails中创建其他模型时自动生成模型

在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

回答

0

您要创建节约@video之前的状态,所以它没有@ video.id,因而是无效的有效性规则

3

由于状态取决于视频已有以下,您可能想要在创建视频后创建状态。

您可以在视频回调中或控制器中执行此操作。喜欢的东西:

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 

然后你就不会提及您的控制器状态 - 你会为常保存。

最终的解决方案是使用一个服务对象来协调在创建视频后保存状态。更多在此RailsCast