Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: Making ''show' view and 'edit' view match

Using Rails 2.3.5, Ruby 1.8.7.

Is there any plugin that will make it easier to make my "show" and "edit" and "new" pages have the same look and feel? I'd love to be able to do the following type of thing. Right now, if I add a field to my model, I have to add it to both the edit.html.erb and the view.html.erb. I want to be able to specify the look fairly extensively, but I want "edit" and "show" to look the same (With execeptions between the two, perhaps, but not many.)

Is there any DRY tool for this?

Essentially, I'd like to be able to make my "edit.html.erb" to be:

<% plugin_form_helper_for @model do |form_helper| %>
  <%= render :partial => 'common_look', :locals => {:helper => form_helper} %>
<% end %>

and the show.html.erb be:

<% plugin_show_helper_for @model do |show_helper| %>
  <%= render :partial => 'common_look', :locals => {:helper => show_helper} %>
<% end %>

Then the "form_helper" and "show_helper" would implement the same interfaces (with some ability to branch to make slight differences between the layout/look of the two.)

like image 740
Thomas Andrews Avatar asked Mar 31 '11 18:03

Thomas Andrews


2 Answers

There is a plugin!

https://github.com/codez/dry_crud

It's very flexible.. just make sure you use the right version for rails 2.3

like image 84
amitkaz Avatar answered Nov 15 '22 20:11

amitkaz


I do something like what you're describing with custom input/display helper functions. For a simplified example, you could have a function you would call like this:

<%= my_field_helper(:model, :field_name) %>

And in your controller, you set a @context variable to either :show or :edit. The helper code contains a switch on @context, and if it's :edit, it outputs something like

<li>
    <label>Translation of Field</label>
    <input name="model[field_name]" value="???" />
</li>

(possibly use a generic @model variable in all your controllers, so the same function can be used on all your pages - or pass @my_model to the function itself) but when @context is :show (or maybe by default), it outputs something like this:

<li>
    <span class="label">Translation of Field</label>
    <span class="value">Field Value</span>
</li>

So now you can use the same exact code to show all your fields! You'll probably want to pull that code out into a partial, so you can easily have it wrapped in a form for edit, but not for show, but the critical bit is accomplished - if you need to add/move/delete fields, there's only one place you have to do it in.

Hope this helps!

like image 37
Xavier Holt Avatar answered Nov 15 '22 18:11

Xavier Holt