Привет, ребята, я новичок в Ruby, пытаясь создать сайт, и это происходит.ActiveRecord :: UnknownAttributeError в LinksController # new
Я действительно перепутал, почему это не работает. Я здесь читаю темы других народов, которые действительно не нашли хорошего решения.
unknown attribute 'user_id' for Link.
Rails.root: c:/sites/rubbit
Application Trace | Framework Trace | Full Trace
app/controllers/links_controller.rb:18:in `new'
Request
Я думаю, что проблема началась после того, как я перешел с Links.new в current_user.links.build
LinksController
class LinksController < ApplicationController
before_action :set_link, only: [:show, :edit, :update, :destroy]
before_filter :authenticate_user!, :except => [:index, :show]
# GET /links
# GET /links.json
def index
@links = Link.all
end
# GET /links/1
# GET /links/1.json
def show
end
# GET /links/new
def new
@link = current_user.links.build
end
# GET /links/1/edit
def edit
end
# POST /links
# POST /links.json
def create
@link = current_user.links.build(link_params)
respond_to do |format|
if @link.save
format.html { redirect_to @link, notice: 'Link was successfully created.' }
format.json { render :show, status: :created, location: @link }
else
format.html { render :new }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /links/1
# PATCH/PUT /links/1.json
def update
respond_to do |format|
if @link.update(link_params)
format.html { redirect_to @link, notice: 'Link was successfully updated.' }
format.json { render :show, status: :ok, location: @link }
else
format.html { render :edit }
format.json { render json: @link.errors, status: :unprocessable_entity }
end
end
end
# DELETE /links/1
# DELETE /links/1.json
def destroy
@link.destroy
respond_to do |format|
format.html { redirect_to links_url, notice: 'Link was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_link
@link = Link.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def link_params
params.require(:link).permit(:title, :url)
end
end
Модель пользователя
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :links
end
Модель Link
class Link < ActiveRecord::Base
belongs_to :user
end
У меня действительно нет подсказки, если мне нужно включить больше.
EDIT
DB/перенос файлов ...
я может отсутствовать некоторые, но когда я "грабли БД: мигрировать" ничего не происходит ..
2 файлов
_create_links
class CreateLinks < ActiveRecord::Migration
def change
create_table :links do |t|
t.string :title
t.string :url
t.timestamps null: false
end
end
end
И
_devise_create_users
class DeviseCreateUsers < ActiveRecord::Migration
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
До сих пор не работает же ошибки ActiveRecord :: UnknownAttributeError в LinksController # новый – carversmind
После добавления этой строки 'расслоение EXEC грабли БД: мигрировать: redo' или' расслоение EXEC грабли db: drop: all db: create: all db: migrate'. Вы должны убедиться, что в таблице ссылок есть столбец 'user_id'. –
Я вижу, что мы отбрасываем базу данных и воссоздаем ее с земли, потому что я добавил пользователя. Но если у вас есть время или знаете, где я могу найти ответ, почему я не могу добавить: пользователь к текущей миграции? – carversmind