dimanche 28 juin 2015

How to create an association between devise user model and new model in rails?

I can easily do singnin and singup process in my application but I am not able to understand how to pass user_id in my new model. After integrating devise successfully I followed the following steps:

Generate new model with the name of book

rails generate model books name:string users:references

It generated book class in models folder along with migration class.

Model class

class Book < ActiveRecord::Base
 belongs_to :user
end

Migration class

class CreateBooks < ActiveRecord::Migration
 def change
  create_table :books do |t|
  t.string :name
  t.references :user, index: true, foreign_key: true
  t.timestamps null: false
  end
end

Now, I add

has_many :books, :dependent => :destroy

in user model class to make a proper one to many association.

After creating these classes I run rake db:migrate and it created a new schema in the project. After creating schema I wrote seed file to confirm whether my database is working or not. It was working fine. I can see the new entries in my Book and user table along with user_id in Book table.

Routes class

sampleApplicationUI::Application.routes.draw do
 devise_for :users
 resources :books, except: [:edit]
end

Now, I added a book_controller class and here is the code:

Book controller class

class BooksController < ApplicationController
before_action :authenticate_user!

 def index
  @book = Book.all
 end

def new
 @book = Book.new
end

def create
 @book = Book.new(filtered_params)
 if @book.save
   redirect_to action: 'index'
 else
   render 'new'
 end
end

private
def filtered_params
 params.require(:book).permit(:name, :user_id)
end
....

books/new.html.erb

<%= form_for @book, as: :book, url: book_path do |f|  %>

<div class="form-group">
  <%= f.label :Name %>
  <div class="row">
    <div class="col-sm-2">
      <%= f.text_field :name, class: 'form-control' %>
    </div>
  </div>
</div>

  <div class="row">
  <div class="col-sm-6">
    <%= f.submit 'Submit', class: 'btn btn-primary' %>
  </div>
</div>

I followed some blogs and they were mentioning to do following changes in book_controller class to access user_id and save into book table:

changes in book controller class

def new
  @book = Book.new(user: current_user)
end

but here I am getting No variable defined current_user :(

Please let me know what I am doing wrong here and How can i access user.user_id in book controller class.

Thanks for your time!

Aucun commentaire:

Enregistrer un commentaire