【发布时间】:2019-03-25 14:44:46
【问题描述】:
我将@booking 与用户(称为“booker”)一起保存。在@booking.save 之后,我可以在命令行中检索@booking.booker,显示用户的所有属性(电子邮件、密码、ID 等)。然而,在离开 create 方法后,无法检索它(例如从节目中):@booking.booker = nil。 我想这是由于我的预订模型中的一个错误:我有belongs_to 和has_many_through。如果错误来自这里,如何在不更改所有数据库的情况下解决它?
booking_controller.rb
class BookingsController < ApplicationController
before_action :set_booking, only: [:show, :edit, :update ]
before_action :set_booking_format, only: [:destroy ]
def index
end
def my_bookings
@bookings = BookingPolicy::Scope.new(current_user, Booking).scope.where(booker: current_user)
end
def show
authorize @booking
end
def new
@garden = Garden.find(params[:garden_id])
@booking = Booking.new
authorize @booking
end
def create
@garden = Garden.find params[:garden_id]
@booking = @garden.bookings.build(booker: current_user)
authorize @booking
if @booking.save
redirect_to garden_booking_path(@booking, current_user)
end
end
def update
end
private
def set_booking
@booking = Booking.find(params[:id])
end
def set_booking_format
@booking = Booking.find(params[:format])
end
def booking_params
params.require(:booking).permit(:garden_id, :booker_id, :date)
end
end
booking.rb
class Booking < ApplicationRecord
belongs_to :garden
belongs_to :booker, class_name: "User"
end
花园.rb
class Garden < ApplicationRecord
belongs_to :user
has_many :bookings, dependent: :destroy
end
用户.rb
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :gardens
has_and_belongs_to_many :bookings
end
schema.rb
create_table "bookings", force: :cascade do |t|
t.date "date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "garden_id"
t.integer "booker_id"
t.index ["garden_id"], name: "index_bookings_on_garden_id"
end
create_table "gardens", force: :cascade do |t|
t.string "title"
t.text "details"
t.integer "surface"
t.text "address"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.text "availabilities"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "admin", default: false
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "bookings", "gardens"
end
【问题讨论】:
标签: ruby-on-rails database controller foreign-keys save