Topic: Refactoring into a Helper with place holder

I am trying to DRY some code that I use to render a list of links list. The code is rendered in the congregation view. I'm still learning and this code admittedly sucks but the issue here is not the code (even though it probably is) but how to create a helper. This was my first rails project and I had to fit the project to existing data.

code in the view: (this will be repeated multiple times for each controller a1..a(n)

<% if @congregations.a1_id.nil? %>
<ul>
<%= link_to "", {:controller => :a1, :action => :new, :id => @congregations.id}, :class => 'createButt' -%>
</ul>

<% else %>
<ul>
  <%= link_to "", {:controller => :a1, :action => :edit, :id => @congregations.a1_id}, :class => 'editButt' -%>           
  <%= link_to "", {:controller => :a1, :action => :delete, :id => @congregations.a1_id},  :confirm => "Are you sure you want to delete A1?", :class => 'deleteButt' -%>
</ul>

<% end %>


Essentially there is a main congregation and each congregation can have 1 unique "sub-controller" called a1,a2,a3..a(n) etc. which is linked via the congregations a1_id,a2_id,a3_id column.

So in the view I first check to see if the @congregations.a1_id.nil?

If it is nil then I render the create link and pass it the congregations id so that in the a1 controller can populate the @congregation.a1_id column when it is saved.

If the @congregations.a1_id does exist then I render the "edit" and "destroy" links instead.

My problem is that I'm new to Rails and have a general groking of the system but am now tackling Helpers and Ruby syntax in general.

I don't know if its possible to pass a helper to pass the "a1" part in as a variable and then insert it into the @congregations.a1_id portion of the if clause. I was able to successfully change the link_to statements with a helper to accept the passed in variable but am scratching my head about how to do the initial nil? check.

Ideally I'd like to be able to use a helper and iterate though a1..a(n) and just pass in the controller name and the action. Any help that can be given is appreciated. Hopefully you're not shaking your head at my ineptitude at this point and have a solution.  I've been racking my brian and googling for quite some time now and decided to ask for help here because railsforum.com is the best.

"If I'd asked my customers what they wanted, they'd have said a faster horse." - Henry Ford

Re: Refactoring into a Helper with place holder

What version of Rails are you using?

Last edited by goodroot (2009-03-13 17:41:12)

Re: Refactoring into a Helper with place holder

2.2.2

"If I'd asked my customers what they wanted, they'd have said a faster horse." - Henry Ford