Rahul Shah
Rahul Shah

Reputation: 165

how to pass object from one controller to another

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.

Upvotes: 0

Views: 261

Answers (2)

Tim Kretschmer
Tim Kretschmer

Reputation: 2280

not really related, but want to help you to have more effective code.

istead of

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

you can write

def get_book
  Book.new as_json.except(*[:id, :created_at, :updated_at])
end

and just for the record: please dont use @var in controllers if you are just redirecting. only use @var if you use them inside a template.

have a nice day!

Upvotes: 0

General Failure
General Failure

Reputation: 2597

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

Upvotes: 1

Related Questions