Home > front end >  Custom model editing for Rails
Custom model editing for Rails

Time:10-08

Suppose I have a Book model in Rails, and this model as a resources has predefined routes e.g. /books/:id/edit.

Now, in my app I wish to show a list of books and add an edit button where everyone can edit the book but only one specific field. I wish to achieve this by rendering a different view, using a different route and a different controller.

How should I define the route so that this works, i.e. the id of the Book instance is passed as needed?

CodePudding user response:

Sounds like you can keep

rails g model book field_one field_two
rails g controller books
# routes.rb
resources :books
patch 'common_update/:id', to: 'books#common_update'

if you specifically want to hit another controller then you can just create a different one (rails g contoller_name) and replace books in the routes with contoller_name (note that the generator takes a plural!).

# books_controller.rb
def common_update
  @book = Book.find(params[:id])
  if @book.update(common_params)
    # do something
  else
    # do something else
  end
end

def common_params
  params.require(:book).permit(:field_one) # but not field_two !
end

As for views, you can perhaps conditionally render the form for the owner (the user who created the book) and the form for everyone else. If you want a separate view/show you can also just add the route (get 'common_show', to: 'controller_name#common_show') plus a view file in the correct folder : 1:

  • Related