【发布时间】:2019-06-08 05:21:58
【问题描述】:
我目前正在尝试在控制器中创建photo。但是,没有保存该实例。我传递了正确的参数,但不确定为什么没有被保存。
18: def create
19: @photo = Photo.new(photo_params)
=> 20: binding.pry
21: if @photo.save
22: redirect_to @photo
23: else
24: render "new"
25: end
26: end
[1] pry(#<PhotosController>)> Photo.new(photo_params)
=> #<Photo:0x00007fefafb9b058 id: nil, user_id: nil, location: "New York", description: "something somethings", created_at: nil, updated_at: nil>
正如你在上面看到的,传递的是参数,但没有传递 id 并且 user_id 也是 nil,是不是因为没有建立关联?
class PhotosController < ApplicationController
def index
@photos = Photo.all
end
def show
@photo = Photo.find(params[:id])
end
def new
@photo = Photo.new
end
def edit
@photo = Photo.find(params[:id])
end
def create
@photo = Photo.new(photo_params)
if @photo.save
redirect_to @photo
else
render "new"
end
end
def update
@photo = Photo.find(params[:id])
respond_to do |format|
if @photo.update(photo_params)
format
.html { redirect_to @photo, notice: 'Post was successfully updated.' }
else
format.html { render :edit }
end
end
end
private
def photo_params
params.require(:photo).permit(
:location,
:description,
:image,
)
end
end
这是照片的控制器。在这里我有新的和创造的。在create 我正在传递参数来创建照片。由于以下关联,我想知道我是否应该从当前用户那里传递这个。
class Photo < ApplicationRecord
has_one_attached :image
belongs_to :user
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :photos
has_one :profile
accepts_nested_attributes_for :profile
end
我这里有以下型号。一个用户有很多张照片,一张照片属于该用户。
class CreatePhotos < ActiveRecord::Migration[5.2]
def change
create_table :photos do |t|
t.references :user, foreign_key: true
t.string :location
t.string :description
t.timestamps
end
end
end
就照片迁移而言。我认为我不必将:image 添加到表中,因为ActiveStorage 通过has_one_attached 方法处理了这一点。不知道是什么问题?
【问题讨论】:
-
请不要发布文本截图,在您的问题中包含文本本身。您还需要显示
photo_params包含的内容,我们无法根据发布的单个 sn-p 代码进行有意义的评论。 -
还不错,会更新帖子。
-
@meagar 进行了更改。
标签: ruby-on-rails ruby activerecord