【问题标题】:Auto generate models on creation of other models in Ruby on Rails在 Ruby on Rails 中创建其他模型时自动生成模型
【发布时间】:2013-05-09 21:37:43
【问题描述】:

我有一个名为 Video 的模型,它有很多状态。我想创建每种状态并将其添加到 VideosController 的 def create 中的@video.statuses。

在 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

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 validation activerecord has-many


    【解决方案1】:

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

    您可以在视频回调中或在控制器中执行此操作。比如:

    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

    【讨论】:

      【解决方案2】:

      您正在尝试在保存@video 之前创建状态,因此它没有@video.id,因此按照您的验证规则无效

      【讨论】:

        猜你喜欢
        • 2013-04-23
        • 2013-04-18
        • 2014-08-23
        • 2014-02-16
        • 1970-01-01
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 2011-08-01
        相关资源
        最近更新 更多