我在 Rails 应用程序中工作,其中 Photo 和 User 是主要模型。它们是关联的,照片属于用户,用户有很多照片。
通过 API(邮递员),我可以使用 user_id 正确地为照片创建新记录。但是我无法通过界面做同样的事情,因为我遇到了这个错误
不允许的参数::user_id
照片控制器.rb
class Api::PhotosController < ApplicationController
skip_before_action :verify_authenticity_token
respond_to :json
# before_action :set_photo
def index
photos = Photo.all
render json: photos, status: 200
end
def show
end
def create
photo = Photo.new(
title: photo_params[:title],
image: photo_params[:image],
user_id: photo_params[:user_id]
)
if photo.save
render json: photo, status: 200
else
render json: {error: "there was an error"}
end
end
private
def photo_params
params.permit([
:title,
:image,
:user_id
])
end
def set_photo
@photo = Photo.find(params[:id])
end
end
照片表格
<%= form_with(model: photo, local: true) do |form| %>
<% if photo.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(photo.errors.count, "error") %> prohibited this photo from being saved:</h2>
<ul>
<% photo.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group">
<%= form.label :image %>
<%= form.text_field :image, class: 'form-control' %>
</div>
<div class="form-group">
<%= form.label :title %>
<%= form.text_field :title, class: 'form-control' %>
</div>
<div class="form-group">
<%= form.label :user_id %>
<%= form.number_field :user_id, class: 'form-control' %>
</div>
<div class="form-group">
<% if photo.persisted? %>
<div class="float-right">
<%= link_to 'Destroy', photo, method: :delete, class: "text-danger", data: { confirm: 'Are you sure?' } %>
</div>
<% end %>
<%= form.submit class: 'btn btn-primary' %>
<% if photo.persisted? %>
<%= link_to "Cancel", photo, class: "btn btn-link" %>
<% else %>
<%= link_to "Cancel", photos_path, class: "btn btn-link" %>
<% end %>
</div>
<% end %>
通过邮递员的示例电话
并通过 Rails 控制台输出最后一条记录
3.0.0 :002 > Photo.last
Photo Load (16.6ms) SELECT "photos".* FROM "photos" ORDER BY "photos"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> #<Photo id: 31, image: "sampleforSO", title: "sampleforSO", created_at: "2021-02-06 15:02:05.153170000 +0000", updated_at: "2021-02-06 15:02:05.153170000 +0000", user_id: 1>
3.0.0 :003 >
PS:与:
Rails 版本 6.1.1 Ruby 版本 ruby 3.0.0p0