我的控制器:
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
我在控制器中的参数:
def article_params
params.require(:article).permit(:title, :brief, :posted_by, :posted_at, :posted_from, :image_file_name)
end
返回此错误,我认为它与控制器参数有关,但我不太确定。
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 (?, ?, ?, ?, ?, ?, ?, ?)
答案 0 :(得分:1)
我相信你没有使用任何宝石进行文件上传。
<%= form_for @article, {},:html => {:multipart => true } do |f| %>
<p>
<%= f.label :Image %><br/>
<%= f.file_field 'file' %>
<%= f.submit "Upload" %>
</p>
<% end %>
在您的创建操作中添加此内容并上传到相同的服务器位置/资产/图像
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