我正在构建一个博客应用程序。我有一个帖子控制器我在视图标题,正文和文件中有三个字段..我将这个文件属性传递给我的模型,在那里我试图使用foreach获取数据但无法要做到这一点。获取此错误未定义的方法[] for ActionDispatch :: Http :: UploadedFile:0x000000035a1970
[post_Controller.rb]
class PostsController < ApplicationController
before_action :authenticate_user!
def index
@posts = Post.user_post(current_user).order('created_at DESC').paginate(:page => params[:page], :per_page => 5)
end
def new
@post = Post.new
end
def show
@post = find_params
end
def create
@post = Post.new(post_params)
@post.user = current_user
if @post.save
Post.upload(params[:post][:files])
redirect_to @post
else
render 'new'
end
end
def edit
@post = find_params
end
def update
@post = find_params
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = find_params
@post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:title, :body)
end
def find_params
Post.find(params[:id])
end
end
<br>
[post.rb]
class Post < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
validates :title, presence: true, length: {minimum: 5}
validates :body, presence: true
def self.user_post(id)
role = User.find_role(id)
if role == 'admin'
Post.all
elsif role == 'user'
Post.where(user_id: id)
elsif role == 'developer'
end
end
**#########at this point i am getting error#####**
def self.upload(files)
k=files[:post][:title]
end
end
[帖/ _form.html.erb]
<%= form_for @post,html: { multipart: true } do |f| %>
<% if @post.errors.any? %>
<div id="errors">
<h2><%= pluralize(@post.errors.count, "error") %> prevented this post from saving:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.label :title %><br>
<%= f.text_field :title %><br>
<br>
<%= f.label :body %><br>
<%= f.text_field :body %><br>
<br>
<%= f.label :files %><br>
<%= f.file_field :files %><br>
<%= f.submit %>
<% end %>
答案 0 :(得分:2)
您已将params[:post][:files]
传递给upload
方法,因此您不再需要[:post][:files]
。您可以直接使用files
:
def self.upload(files)
files.each do |file|
# Do something with file
end
end
此外,<ActionDispatch::Http::UploadedFile:0x00000003d40b68>
表示您只有1个上传文件,而不是集合,因此您无法使用each
。您必须更改表单以允许上载多个文件。
试试这个:
<%= f.file_field :files, :multiple => true %>