Ruby on rails, смена недавно созданного эшафота

Я работаю над приложением в Ruby on Rails (5.1.4). Недавно я создал скаффолд для пользователя с двумя параметрами: имя пользователя и имя. Через некоторое время я сменил имя пользователя на Index. Теперь есть проблема с созданием нового пользователя. Очевидно - в каждой модели, контроллере и т. д. Я знаю, что есть имя пользователя - я изменил его на индекс. Вопрос - смогу ли я это сделать? Или я должен создать новый скаффолд с правильными параметрами? Если да, то как мне это сделать? Я не хочу терять работу с контроллерами и представлениями.

Итак, вот как я создал скаффолд:

rails generate scaffold Student index:string name:string

Это ошибка, которую я получаю каждый раз, когда пытаюсь создать нового пользователя:

Ошибка

И изменения, которые я сделал:

приложение/модели/user.rb

class User < ApplicationRecord
    has_and_belongs_to_many :movies, :join_table => :users_movies
    has_many :topics
    has_many :posts

    has_secure_password

    validates :name, presence: true, uniqueness: true, length: { in: 3..50 }
    validates :index, presence: true, length: { is: 6 }, uniqueness: true
    validates :password, presence: true, length: { minimum: 6 }

    def follows?(movie)
        self.movies.include?(movie)
    end
end

приложение/просмотры/пользователи/_form.html.erb

<%= form_with(model: user, local: true) do |form| %>
  <% if user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :index %>
    <%= form.text_field :index, id: :user_index %>
  </div>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, id: :user_name %>
  </div>

  <div class="field">
    <%= form.label :password %>
    <%= form.password_field :password, id: :users_password %>
  </div>

  <div class="field">
    <%= form.label :password_confirmation %>
    <%= form.password_field :password_confirmation, id: :user_password_confirmation %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

приложение/представления/пользователи/_user.json.builder

json.extract! user, :id, :index, :name, :created_at, :updated_at
json.url user_url(user, format: :json)

приложение/просмотры/пользователи/index.html.erb

<p id="notice"><%= notice %></p>

<h1>Users</h1>

<table>
  <thead>
    <tr>
      <th>Index</th>
      <th>Name</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.index %></td>
        <td><%= user.name %></td>
        <td><%= link_to 'Show', user %></td>
        <td><%= link_to 'Edit', edit_user_path(user) %></td>
        <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New User', new_user_path %>

приложение/представления/пользователи/show.html.erb

<p id="notice"><%= notice %></p>

<p>
  <strong>Index:</strong>
  <%= @user.index %>
</p>

<p>
  <strong>Name:</strong>
  <%= @user.name %>
</p>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

приложение/контроллеры/user_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  # GET /users
  # GET /users.json
  def index
    @users = User.all
  end

  # GET /users/1
  # GET /users/1.json
  def show
  end

  # GET /users/new
  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
        format.json { render :show, status: :created, location: @user }
      else
        format.html { render :new }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
        format.json { render :show, status: :ok, location: @user }
      else
        format.html { render :edit }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:index, :name, :password, :password_confirmation)
    end
end

БД/schema.rb

# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.

ActiveRecord::Schema.define(version: 20180113170026) do

  create_table "movies", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string "body"
    t.integer "user_id"
    t.integer "topic_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["topic_id"], name: "index_posts_on_topic_id"
    t.index ["user_id"], name: "index_posts_on_user_id"
  end

  create_table "topics", force: :cascade do |t|
    t.string "title"
    t.integer "user_id"
    t.integer "movie_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["movie_id"], name: "index_topics_on_movie_id"
    t.index ["user_id"], name: "index_topics_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "index"
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "password_digest"
    t.index [nil], name: "index_users_on_index", unique: true
  end

  create_table "users_movies", id: false, force: :cascade do |t|
    t.integer "user_id"
    t.integer "movie_id"
    t.index ["movie_id"], name: "index_users_movies_on_movie_id"
    t.index ["user_id"], name: "index_users_movies_on_user_id"
  end

end

БД/мигрировать/20171125194647_create_users.rb

class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :index
      t.string :name

      t.timestamps
    end
  end
end

person Ins0maniac    schedule 14.01.2018    source источник
comment
Вы пытались восстановить базу данных?   -  person Hatik    schedule 14.01.2018


Ответы (1)


Вы можете создать миграцию, чтобы переименовать атрибут в вашей модели, например:

$ rails g migration rename_index_to_username

Внутри файла миграции укажите модель, которую нужно обновить, в качестве первого аргумента для rename_column, затем имя старого атрибута и новое:

class RenameIndexToUsername < ActiveRecord::Migration[5.1]
  def change
    rename_column :users, :index, :username
  end
end

Затем запустите rails db:migrate, чтобы сохранить изменения.

После этого ошибка будет сохраняться, потому что в других файлах все еще есть ссылки на индекс:

  • Сначала отредактируйте user_params, созданные Rails, заменив index на имя пользователя.
  • Замените на странице показа и индекса любую ссылку на атрибут индекса на имя пользователя.
  • Замените в форме хелпер text_field, указывающий на индекс, на имя пользователя.
  • Наконец, замените также валидацию в модели на validates :username ...
person Sebastian Palma    schedule 14.01.2018