【问题标题】:Error 404 when uploading a file caused by error in update function由于更新功能错误导致上传文件时出现错误 404
【发布时间】:2017-06-08 23:23:11
【问题描述】:

我很难弄清楚我的代码有什么问题。基本上,我使用的是Dropzone-js's 文件上传器,它使用拖放。我无法上传文件,因为它返回给我404 error。 我搜索了我的日志,发现我的controller 有问题,在update 函数中。

控制器

class ChatRoomsController < ApplicationController
before_action :authenticate_user!
before_action :set_room, only: [:index, :new, :create, :show, :edit, :signal]
before_action :set_participant, only: [:signal]

def index
  @chat_rooms = ChatRoom.all
end

def show
  # Show room messages
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:id])
  @message = Message.new

  @chat_room.participant?(current_user)

  # TODO: get participant only once
  if params[:guid]
    if @participant = User.find(params[:guid])
      @participant.joined_at = Time.now
      @chat_room.add_to_call(@participant)
    end
  elsif params[:del]
    if @participant = User.find(params[:del])
      @chat_room.remove_from_call(@participant)
    end
  end

  response = {
      room: @chat_room,
      # Get all call participants
      users: @chat_room.call_users,
      signals: deliver_signals!
  }

  respond_to do |format|
    format.html
    format.json { render json: response }
  end

end

def new
  @chat_room = ChatRoom.new
end

def edit
  # Empty
end

def create
  @chat_room = current_user.chat_rooms.build(chat_room_params)
  if @chat_room.save
    @group_room.users << current_user
    redirect_to chat_rooms_path
  else
    render 'new'
  end
end

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  if @chat_room.update_resource(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

def signal
  signal = signal_params
  signal[:chat_room] = @chat_room
  signal[:sender] = User.find(signal[:sender])
  signal[:recipient] = @participant
  logger.info('Signal is ' + signal.to_param)
  ChatRoomSignal.create! signal
  head 204
end

def deliver_signals!
  data = ChatRoomSignal.where recipient: @participant

  # Destroy the signals as we return them, since they have been delivered
  result = []
  data.each do |signal|
    result << {
        signal_type: signal.signal_type,
        sender_guid: signal.sender_id,
        recipient_guid: signal.recipient_id,
        data: signal.data,
        chat_room_id: signal.chat_room_id,
        timestamp: signal.created_at
    }
  end
  data.delete_all
  result
end

private

def set_participant
  @participant = User.find(params[:user_id])
rescue ActiveRecord::RecordNotFound
  # Retry with ID as GUID
  @participant = User.where(id: params[:user_id]).first
  raise unless @participant
end

def set_room
  @chat_room = ChatRoom.includes(:messages).find_by(id: params[:chat_room_id])
end

def chat_room_params
  params.require(:chat_room).permit(:title, :image)
end

def signal_params
  params.permit(:sender, :signal_type, :data)
end

文件上传的 HTML 代码

<div class="panel-body">
  <%= form_for @chat_room, html: { multipart: true, class: "dropzone", id: "my-dropzone"} do |f| %>

    <div class="dz-message needsclick">
      <h3>Drop a file here</h3> or <strong>click</strong> to upload
    </div>

    <div class="fallback">
      <% f.file_field :image, as: :file %>
      <%= f.submit "Upload your file" %>
    </div>
 <% end %>
</div>

错误:

[ActionCable] [test@test.com] ChatRoomsChannel is transmitting the subscription confirmation
[ActionCable] [test@test.com] ChatRoomsChannel is streaming from chat_rooms_1_channel
Started PATCH "/chat_rooms/1" for 127.0.0.1 at 2017-06-09 01:44:26 +0200
Processing by ChatRoomsController#update as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"p8KEWBx7fmJmEhHgINmp5rnj+PVwGXfbPHxslSaA4Z/5zA6HIJzxeBjwcz/+GcDEQKKwPwjXNJVnBtfq7xu2qw==", "chat_rooms"=>{"image"=>#    <ActionDispatch::Http::UploadedFile:0x007f640e58f5b0 @tempfile=#<Tempfile:/tmp/RackMultipart20170609-2887-1nuat54.png>, @original_filename="Screenshot from 2017-04-12 12-47-21.png", @content_type="image/png", @headers="Content-Disposition: form-data; name=\"chat_rooms[image]\"; filename=\"Screenshot from 2017-04-12 12-47-21.png\"\r\nContent-Type: image/png\r\n">}, "id"=>"1"}
  [1m[36mUser Load (0.2ms)[0m  [1m[34mSELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?[0m  [["id", 1], ["LIMIT", 1]]
  [1m[36mChatRoom Load (0.2ms)[0m  [1m[34mSELECT  "chat_rooms".* FROM "chat_rooms" WHERE "chat_rooms"."id" = ? LIMIT ?[0m  [["id", nil], ["LIMIT", 1]]
Completed 404 Not Found in 7ms (ActiveRecord: 0.3ms)



ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>nil}):

app/controllers/chat_rooms_controller.rb:62:in `update'

第 62 行

@chat_room = ChatRoom.find(id: params[:chat_room_id])

所以我的controller 似乎找不到id 参数,但我不明白为什么。这可能是导致我的文件返回404 error的错误。

感谢您花时间阅读我的帖子。

【问题讨论】:

  • 日志显示什么?检查参数,很可能是你在chat_room_id键中没有得到任何值。
  • 更新错误日志

标签: ruby-on-rails carrierwave dropzone.js


【解决方案1】:

您使用了错误的密钥来获取id,请尝试使用params[:id]

@chat_room = ChatRoom.find(params[:id])

还要注意id: 已被删除,因为find 将寻找作为参数提供的id

另外,您应该更新您的 chat_room_params 方法:

def chat_room_params
 params.require(:chat_rooms).permit(:title, :image)
end

由于您只更新 2 个属性,您可以像这样重构您的 update 方法:

def update
  @chat_room = ChatRoom.find(id: params[:chat_room_id])
  @chat_room.title = chat_room_params[:title]
  @chat_room.image = chat_room_params[:image]

  if @chat_room.save(chat_room_params)
    flash[:success] = 'test'
  else
    render 'edit'
  end
end

【讨论】:

  • 好的,看来您正在做某事。我现在有一个新错误:ActiveRecord::RecordNotFound (Couldn't find ChatRoom with 'id'={:id=>"1"}): 但我不太明白,我当前的聊天室的 id 等于1,所以我不明白为什么它搜索 id => 1
  • @xZeasy 检查更新的答案,从find 中删除了id:,这会导致错误。
  • 还有一个新错误:ActionController::ParameterMissing(参数丢失或值为空:chat_room):现在我有一个错误400错误请求,不再是404
  • 它是 ligne 115 "app/controllers/chat_rooms_controller.rb:115:in `chat_room_params'"。这就是 chat_room_params 所在的地方,chat_room 是必需的参数
  • @xZeasy 我现在看到了,你必须用require(:chat_rooms) 更新你的chat_room_params
【解决方案2】:

您的params[:chat_room_id] 似乎是一个哈希值..

试试

@chat_room = ChatRoom.find(id: params[:chat_room_id][:id])

【讨论】:

  • 得到一个“NoMethodError (undefined method `[]' for nil:NilClass):”,好像它不喜欢“[:id]”
  • @Gerry 不起作用:ActiveRecord::RecordNotFound(找不到带有 'id'= 的 ChatRoom):
猜你喜欢
  • 1970-01-01
  • 2020-04-02
  • 1970-01-01
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多