How to pass the object from one controller to another

advertisements

I am making an library app which has two models Book and Suggestion. The Suggestion model is used to suggest books to be added to the library.

Now in the Suggestion model, I have added a method to retrieve the book and I wish to add this book into the database.

The Code for the above are as follows:

Suggestion.rb

def get_book
        h = as_json
        h.delete("id")
        h.delete("created_at")
        h.delete("updated_at")
        return Book.new(h)
    end

SuggestionController.rb

def approve
@book = @suggestion.get_book
    redirect_to @book, notice: "Book was successfully added into the database"

But since the @book has not been assigned the id, it is not able to redirect it.

All the other controllers and models are initiated via scaffolding.

How should I retain the information contained in the suggestion and pass it to book controller to add into the database.


You can redirect to new book instead newly created. New book properties You can pass via redirect_to, for example:

redirect_to new_book_path, notice: "Book was successfully added into the database", new_book: @book.to_json

And check new_book parameter in new method:

def new
    if params[:new_book].nil?
        # usual behavior
    else
        @book = Book.new(params[:new_book])
    end
end