문제

I was wondering if the following is possible in rails.

When I update the params [:book] in my app i get the notice 'book checked out', this is passed in the controller like so

def update
@book = Book.find(params[:id])
  if @book.update_attributes(params[:book]) 
   redirect_to books_path, :notice => "You have checked out this book"
  else
   render :action => 'show'
  end
end

i have occasions at present when params are updated, when someone checks_out and checks_in a book (I have a library app). Either true or false is passed.. At the moment i get the same message.

Can I create a method to show a different notice dependent upon whether true or false is passed, so something like

def check_message
if book.check_out == true
 :notice => 'You have checked out the book'
else
 :notice => 'you have checked the book back in' 
end

then in the controller

def update
@book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
   redirect_to books_path, check_book
  else
   render :action => 'show'
  end
end

Im sure thats wrong, but my next question would how would i use that method in the controller, is there a better way of doing it?

Any advice/help appreciated

Thanks

도움이 되었습니까?

해결책

I would propose you to go with something like this:

@book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
   redirect_to books_path, :notice => "You have checked #{@book.checked_out ? 'out the book' : 'the book back in'}"
  else
   render :action => 'show'
  end
end

Or if you still want to use method from model:

@book = Book.find(params[:id])
  if @book.update_attributes(params[:book])
   redirect_to books_path, :notice => @book.checek_message
  else
   render :action => 'show'
  end
end


# book model
def check_message
  book.check_out ? 'You have checked out the book' : 'you have checked the book back in' 
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top