gpt4 book ai didi

ruby-on-rails - Rails file_field 不上传图像

转载 作者:太空宇宙 更新时间:2023-11-03 16:26:52 25 4
gpt4 key购买 nike

我的 Controller :

class ArticlesController < ApplicationController

def index
@articles = Article.organise
end

def show
@article = Article.find(params[:id])
end

def edit
@article = Article.find(params[:id])
end

def update
@article = Article.find(params[:id])
@article.update(article_params)
redirect_to @article
end

def new
@article = Article.new
end

def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end

def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end


private

def article_params
params.require(:article).permit(:title, :brief, :posted_by, :posted_at, :posted_from, :image_file_name)
end



end

我的看法:

  <p>
<%= f.label :Image %><br/>
<%= f.file_field :image_file_name %>
</p>

我的模型:

class Article < ActiveRecord::Base

def self.organise
order("posted_at desc")
end



end

我在 Controller 中的参数:

def article_params
params.require(:article).permit(:title, :brief, :posted_by, :posted_at, :posted_from, :image_file_name)
end

正在返回此错误,我认为它与 Controller 参数有关,但我不太确定。

ActiveRecord::StatementInvalid in ArticlesController#create
TypeError: can't cast ActionDispatch::Http::UploadedFile to string: INSERT INTO "articles" ("brief", "created_at", "image_file_name", "posted_at", "posted_by", "posted_from", "title", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?)

最佳答案

我相信您没有使用任何 gem 进行文件上传。

<%= form_for @article, {},:html => {:multipart => true } do |f| %>
<p>
<%= f.label :Image %><br/>
<%= f.file_field 'file' %>
<%= f.submit "Upload" %>
</p>
<% end %>

将此添加到您的创建操作中并上传到相同的服务器位置/assets/images

if params[:article].present?
file = params[:article][:file]
File.open(Rails.root.join('app','assets', 'images', file.original_filename), 'wb') do |f|
f.write(file.read)
end
end

关于ruby-on-rails - Rails file_field 不上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23360919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com