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

怎甘沉沦 提交于 2020-01-04 05:13:11

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/14826383/in-rails-is-it-possible-to-use-the-show-view-as-an-edit-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!