views:

42

answers:

1

For example, I might have an partial something like:

<div>
  <%= f.label :some_field %><br/>
  <%= f.text_field :some_field %>
</div>

which works for edit AND new actions. I also will have one like:

<div>
  <%=h some_field %>
</div>

for the show action. So you would think that all your partials go under one directory like shared or something. The problem that I see with this is that both of these would cause a conflict since they are essentially the same partial but for different actions so what I do is:

<!-- for edit and new actions -->
<%= render "shared_edit/some_partial" ... %>

<!-- for show action -->
<%= render "shared_show/some_partial" ... %>

How do you handle this? Is a good idea or even possible to maybe combine all of these actions into one partial and render different parts by determining what the current action is?

+2  A: 

When I use shared directory, then inside I put model name and my partials have names like this:

shared/person/_show.html.erb
shared/person/_form.html.erb

If you want to have one line to render form or show partial, then you can add helper:

def render_form_or_show(model)
  if edit? || new? 
    return render :partial => "shared/#{model}/form"
  elsif show?
    return render :partial => "shared/#{model}/show"
  end
  return ""
end

If you fallow some rules, like putting your partials in shared directory and then in model directory, and then always have _form for edit and new, and _show for show action, then it will work ;). Of course you need to define edit? etc. methods:

# Application controller
def edit?
  params[:action] == 'edit'
end

Or maybe there is better way to get action name :).

klew
Great answer, thanks!
DJTripleThreat