代码之家  ›  专栏  ›  技术社区  ›  Lee Eather

模型验证方法从服务器rails 5返回错误

  •  0
  • Lee Eather  · 技术社区  · 7 年前

    我有这个方法 micropost.rb ,运行此方法时出现错误。当我提交表单时,我不会从模型中获得错误,而是从 else 控制器 . 这件事似乎有点不对劲 但不明白为什么我从服务器获得回滚事务?

    该方法只是检查用户是否输入并发送了多个字段。

    微孔。rb型

    validate :return_media_field_errors
    
    private 
    
    def return_media_field_errors
      if :img_url? && :video_url? 
        errors.add(:img_url, "Can only submit one field at a time")
      end
    end
    

    Micropost控制器

    def create
      @micropost = current_user.microposts.build(micropost_params)
      if @micropost.save
        flash[:success] = "Micropost created!"
        @micropost  = current_user.microposts.build
        @feed_items = current_user.feed.paginate(page: params[:page])
        render 'static_pages/home'
      else
        @feed_items = []
        render 'shared/error_messages'
      end
    end
    
    private
    
      def micropost_params
        params.require(:micropost).permit(:content, :picture, :picture_cache, :image_url, :video_url, :gif_url)
      end
    

    create_table "microposts", force: :cascade do |t|
      t.text     "content"
      t.integer  "user_id"
      t.datetime "created_at", null: false
      t.datetime "updated_at", null: false
      t.string   "picture"
      t.string   "image_url"
      t.string   "video_url"
      t.string   "gif_url"
      t.index ["user_id", "created_at"], name: "index_microposts_on_user_id_and_created_at"
      t.index ["user_id"], name: "index_microposts_on_user_id"
    end
    

    查看参数

    <div class="media_field_1">    
      Image <%= f.text_field :image_url, class: 'form-control' %>
    </div>
    <div class="media_field_2"> 
      Video <%= f.text_field :video_url, class: 'form-control' %>
    </div> 
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   EJAg    7 年前

    我认为问题在于这一行:

    if :img_url? && :video_url? 
    

    在这里 :img_url? 是符号,不是属性

    self.image_url? 或者只是 image_url ,相同 video_url