Невозможно загрузить фотографии профиля пользователя rails 5 (без драгоценных камней) - PullRequest
0 голосов
/ 17 сентября 2018

Я пытаюсь загрузить пользовательские фотографии на странице пользовательского шоу, относительно новой для проекта rails.Я собираюсь включить в список моих пользователей показ html erb, а также мои пользовательские контроллеры и модель пользователя, а также действия сервера, когда я нажимаю кнопку «обновить».

class UsersController < ApplicationController
    skip_before_action :verify_authentication, only: [:new, :create, :index]


    def create 
        @user = User.new(user_params)

        if @user.save
            session[:user_id] = @user.id
            redirect_to root_path, notice: "User successfully created."
        else
            redirect_to new_user_path, notice: "Something went wrong, please try again."
        end
    end
    def index
    end

    def update
        if current_user != @user_id
            flash[:notice] = "You cannot update this user"
        end
        @user = User.find(params[:id])
        if @user.update_attributes(user_params)
          flash[:notice] = "Profile updated"
          redirect_to @user
        else
          flash[:notice] = "Not uploaded"
          redirect_to @user
        end
    end

    def new
        @user = User.new
    end

    def show
        @user = User.find(params[:id])
        @posts = @user.posts
    end

    def destroy
        if current_user == @user
            @user.destroy
        else
            render json: @user.errors, status: :unprocessable_entity
        end
    end

    private
        def user_params
            params.permit(:username, :password, :photo)
        end
end

Модель пользователя

class User < ApplicationRecord
    has_secure_token :api_token
    has_secure_password
    validates :username, uniqueness: true
    validates :password, presence: true, length: {minimum: 5}
    has_many :posts, dependent: :destroy
    has_many :comments, dependent: :destroy
    has_one_attached :photo
end

Пользователи show.html.erb page

    <h1 class='h3 mt-5 mb-3 font-weight-normal text-center'><%= @user.username %>  </h1>

<% if notice %>
<p><%= notice %></p>
<% end %>


<% if @user.photo.attached? %>
  <p>
    <strong> Profile Photo </strong>
      <%= image_tag @user.photo, style: "max-width: 100px, max-height: 100px"  %>
  </p>
<% end %>

<div class="text-center">
<p> Upload a profile photo: </p>
  <%= form_with model: @user, local:true do |form| %>
    <%= form.label :photo %>
    <%= form.file_field :photo %>
    <%= form.submit %>
  <% end %>
</div>
<div>
<%= link_to 'Back', root_path %>
</div>

<div>
<% @posts.each do |post| %>
    <div class="card border-secondary text-center" style="width: 30rem;">
        <div class="card-body">
          <h3 class="card-title">
          <%= post.question %>
          </h3>
        </div>
          <p class="card-text">
          <%= post.body %>
          </p>
          <p class="card-text">
          <%= link_to 'Show', post_path(post) %>
          </p>
  <% end %>

</div>

И, наконец, сервер, когда я нажимаю на кнопку submit.

Started GET "/users/180" for 127.0.0.1 at 2018-09-17 14:45:03 -0400
Processing by UsersController#show as HTML
  Parameters: {"id"=>"180"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 180], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:18
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 180], ["LIMIT", 1]]
  ↳ app/controllers/users_controller.rb:37
  Rendering users/show.html.erb within layouts/application
  ActiveStorage::Attachment Load (0.2ms)  SELECT  "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ?  [["record_id", 180], ["record_type", "User"], ["name", "photo"], ["LIMIT", 1]]
  ↳ app/views/users/show.html.erb:8
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = ?  [["user_id", 180]]
  ↳ app/views/users/show.html.erb:28
  Rendered users/show.html.erb within layouts/application (4.5ms)
Completed 200 OK in 43ms (Views: 36.9ms | ActiveRecord: 0.9ms)

Я знаю, что оно запускает обновлениеметод в моем usercontroller, потому что в сообщении мигает «Not Uploaded», но в журнале сервера, кажется, предполагается, что он выполняет запрос get вместо put?Я хотел бы достичь этого без каких-либо драгоценных камней.

1 Ответ

0 голосов
/ 19 сентября 2018

Решением стали изменения, выделенные жирным шрифтом:

def update
        if current_user.id != @user_id
            flash[:notice] = "You cannot update this user"
        end
        @user = User.find(params[:id])
        **if @user.photo.attach(user_params[:photo])**
          flash[:notice] = "Profile updated"
          redirect_to @user

        else
          flash[:notice] = "Not uploaded"
          redirect_to @user

        end
end

и comment_params, скорректированные до:

        def user_params
            params.require(:user).permit(:username, :password, :photo, 
            :email)
        end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...