не может связать пользователя с книгой (не может получить доступ к идентификатору пользователя) - PullRequest
1 голос
/ 08 июня 2011

Я использую devise для регистрации и аутентификации пользователей. То, что я пытаюсь сделать, это для пользователя, чтобы войти и иметь возможность добавить книгу в своем профиле. И позже, когда он войдет в книгу, будет показано. Поэтому в моем приложении у меня есть модель пользователя и модель книги. Но у меня проблема с доступом к пользователю на одном из контроллеров. Я получаю исключение неопределенный метод `books 'для nil: NilClass .

VIEW

Home # индекс

   <p >Welcome to the new generation</p>
    <p><%= link_to "Add new Book",:controller =>"book", :action => 'new' %></p>
   <% @books.each do |b| %>
  <p><%= b.author%></p>
 <p><%= b.title%></p>
 <%end%>

ДОМАШНИЙ КОНТРОЛЛЕР

class HomeController < ApplicationController
 def index
 @user = current_user
 @user.books||=Book.new
 @books=@user.books
end
end

КОНТРОЛЛЕР КНИГИ

class BookController < ApplicationController
 def new
@books = Book.new
# redirect_to :controller=>"home" ,:action=>"index"
end

 def create
 @books = Book.new(params[:book])
  if @books.save
    render "home/index"
       #redirect_to :controller=>"home" ,:action=>"index"
  else

        render :action => 'new'
  end
end

просмотр книги

<h1>Book#new</h1>

 <%= form_for(:book) do |f| %>
  <p><%= f.text_field :title %></p>
  <p><%= f.text_field :author %></p>
  <p><%= f.submit "Add book"%> 

КНИЖНАЯ МОДЕЛЬ

class Book < ActiveRecord::Base
belongs_to :user
end

МОДЕЛЬ ПОЛЬЗОВАТЕЛЯ

class User < ActiveRecord::Base
has_many :books
# Include default devise modules. Others available are:
# :token_authenticatable, :lockable, :timeoutable and :activatable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password,         :password_confirmation,:firstname,:lastname,:school,:major,:sex,:zipcode


 end

ROUTE

 Campus::Application.routes.draw do


 get "book/index"

 get "book/edit"

  get "book/new"

  get "home/edit"

  devise_for :users
  resources :book     
  root :to=> "home#index"
  match '/book/new' =>"home#index"
   end

CREATE TABLE

class CreateBooks < ActiveRecord::Migration
  def self.up
create_table :books do |t|
  t.text :title
  t.text :author
  t.integer :user_id, :null => false
  t.timestamps
 end
   add_foreign_key(:books, :users)
 end

def self.down drop_table: книги remove_foreign_key (: books,: users) конец конец

БД СХЕМА

  ActiveRecord::Schema.define(:version => 20110609055608) do

  create_table "books", :force => true do |t|
  t.text     "title"
  t.text     "author"
  t.datetime "created_at"
  t.datetime "updated_at"
  end

  create_table "courses", :force => true do |t|
  t.string   "name"
  t.datetime "created_at"
  t.datetime "updated_at"
  end

  create_table "strong_ins", :force => true do |t|
  t.string   "subject"
  t.string   "topic"
  t.text     "description"
  t.datetime "created_at"
  t.datetime "updated_at"
  end

  create_table "users", :force => true do |t|
  t.string   "email",                               :default => "", :null => false
  t.string   "encrypted_password",   :limit => 128, :default => "", :null => false
  t.string   "password_salt",                       :default => "", :null => false
  t.string   "reset_password_token"
  t.string   "remember_token"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",                       :default => 0
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "firstname"
  t.string   "lastname"
  t.text     "school"
  t.text     "major"
  t.string   "sex"
  t.integer  "zipcode"
 end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name =>      "index_users_on_reset_password_token", :unique => true

  create_table "weak_ins", :force => true do |t|
   t.string   "subject"
   t.string   "topic"
   t.text     "description"
   t.datetime "created_at"
   t.datetime "updated_at"
   end

   end

1 Ответ

2 голосов
/ 08 июня 2011

Чтобы получить зарегистрированного пользователя в контроллерах с помощью devise, просто используйте переменную current_user.Кроме того, отношения между Пользователем и Книгой has_many :books, поэтому current_user.book не существует.

class HomeController < ApplicationController
 def index
  @user = current_user
  @books = @user.books
 end
end
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...