Jason Varga
Jason Varga

Reputation: 1959

In Rails, is it possible to use the show view as an edit view?

New to Rails here, so excuse me if this is simple. I'm having a hard time finding out the answer, which I want to know before I dive in too deep.

The app I'm aiming to build will not really have a differentiation between the 'show' view and the 'edit' view. For the most part, I would have listings of entries (index view) where you would just click straight through to the edit view. No 'show' view is necessary.

It would be like this for the majority of the app. There would still be some sections that would require 'show' views, though.

Is it possible to set up a routing structure like this?

Upvotes: 3

Views: 292

Answers (3)

Marc Baumbach
Marc Baumbach

Reputation: 10473

If a show view isn't necessary, you can simply tell the resource route in routes.rb to not include it, like:

resources :users, :except => :show

If you want to use the same view for both edit and show, in your show action, for example, you can do something like:

def show
  @user = User.find(params[:id])
  render :action => 'edit'
end

This will use the edit.html.erb file when the show action is hit, although in my opinion your best option is to pick a view you plan to use and omit the other in your routes.rb.

If you simply want to share a lot of view code between the two views, but still differentiate them, just make use of Partials for the shared code.

Upvotes: 3

mind.blank
mind.blank

Reputation: 4880

Yes, you don't always have to use all 7 actions.

Example routing:

resources :users, except: :show

Controller:

def edit
  @user = User.find(params[:id])
end

def update
  @user = User.find(params[:id])
  if @user.update_attributes(params[:user])
    redirect_to edit_user_path(@user)
  else
  ...
  end
end

Add the form to the edit view as normal and anything else you would put in your show view.

Upvotes: 3

Mark Swardstrom
Mark Swardstrom

Reputation: 18080

Yes - you'd just add the form partial to the show page. This is pretty common.

Upvotes: 1

Related Questions