【问题标题】:Rails - Model not saving to dbRails - 模型不保存到数据库
【发布时间】:2017-10-23 12:54:57
【问题描述】:

我正在完成这个 airbnb 克隆课程 (https://code4startup.com/projects/build-airbnb-with-ruby-on-rails-level-1),但为了完成我自己的项目而转移了一些注意力;教育营的市场。因此,我添加了一个额外的模型“课程”。它现在有用户>列表>课程。这个 Courses 模型在 rails 控制台中工作,但在我运行服务器时没有保存到我的数据库中。任何建议将不胜感激...

错误信息

ActiveRecord::RecordInvalid in CoursesController#create
Validation failed: Listing must exist

模型

class User < ApplicationRecord
  has_many :listings
  has_many :courses, :through => :listings
end

class Listing < ApplicationRecord
  belongs_to :user
  has_many :courses

  validates :listing_type, presence: true
  validates :course_type, presence: true
  validates :accommodate, presence: true
end

class Course < ApplicationRecord
  belongs_to :listing

  validates :curriculum_type, presence: true
  validates :course_places, presence: true
end

课程负责人

    class CoursesController < ApplicationController

  before_action :set_course, except: [:index, :new, :create]
  before_action :authenticate_user!, except: [:show]

  def index
    @courses = current_user.courses
  end

  def new
    @course = current_user.courses.build
  end

  def create
    @course = current_user.courses.build(course_params)
    if @course.save!
      redirect_to course_listing_path(@course), notice: "Saved..."
    else
      render :new, notice: "Something went wrong..."
    end
  end

  def show
  end


  def listing
  end

  def pricing
  end

  def description
  end

  def photo_upload
  end

  def amenities
  end

  def location
  end

  def update
    if @course.update(course_params)
      flash[:notice] = "Saved..."
    else
      flash[:notice] = "Something went wrong..."
    end
    redirect_back(fallback_location: request.referer)
  end

  private

  def set_course
    @course = Course.find(params[:id])
  end

  def course_params
    params.require(:course).permit(:name, :curriculum_type, :summary, :address, :course_places, :start_date, :finish_date, :price)
  end

end

路线

Rails.application.routes.draw do

  root 'pages#home'

  devise_for :users,
              path: '',
              path_names: {sign_in: 'login', sign_out: 'logout', edit: 'profile', sign_up: 'registration'},
              controllers: { omniauth_callbacks: 'omniauth_callbacks', registrations: 'registrations' }
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  resources :users, only: [:show]
  resources :listings, except: [:edit] do
    member do
      get 'listing'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      get 'amenities'
      get 'location'
    end
  end

  resources :courses, except: [:edit] do
    member do
      get 'listing'
      get 'pricing'
      get 'description'
      get 'photo_upload'
      get 'amenities'
      get 'location'
    end
  end


end

【问题讨论】:

    标签: ruby-on-rails ruby database validation activerecord


    【解决方案1】:

    您可以在下面阅读我的带有# 符号的 cmets

    您正在尝试保存具有 belongs_to listings 的对象 Course,因此预计它具有现有 Listingcourse.listing_id id

    def create
        @course = current_user.courses.build(course_params)
        # You need to set @course.listing_id to an existing Listing
        # You need to find that listing and save it in a variable. 
        # I am not getting into your logic, because your code is confused and need many adjustments
    
        listing = Listing.find() # include hear your logic to find an existing listing from the db
        @course.listing_id = listing.id
        if @course.save!
          redirect_to course_listing_path(@course), notice: "Saved..."
        else
          render :new, notice: "Something went wrong..."
        end
    end
    

    【讨论】:

    • 这对您很有帮助,谢谢。对于“listing = Listing.find()”,最常见的方法是什么?或者有没有办法自动做到这一点,例如点击列表页面上的新课程按钮?
    • @JackRiminton 如果两个模型之间存在关系,并且一个是另一个模型的父级,我将尝试使用嵌套资源guides.rubyonrails.org/routing.html#nested-resources 并将id 作为参数传递给我的@ 987654330@ http post 请求服务器,所以 post 请求应该看起来像/listings/:listing_id/courses 并且它是由动作courses#create 执行的,这样你就可以做到Listing.find(params[:listing_id]) 并且你的资源是resources :listings do resources :courses end
    • @JackRiminton 祝你好运。很快一切都会变得非常清晰。感谢您的积分
    猜你喜欢
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    相关资源
    最近更新 更多