views:

41

answers:

1

I have a view on my current project which does something like the following(in haml):

[email protected] do |horse|
  = render :partial => 'main/votingbox', :locals => {:horse => horse}

The in the _votingbox.html.haml file I have the following:

%div.votingbox
  %span.name= horse.name
  %div.genders
    - if horse.male
      %img{:src => 'images/male.png', :alt => 'Male'} 
    - if horse.female
      %img{:src => 'images/female.png', :alt => 'Female'}
  %div.voting_form
    = form_for(Vote.new, {:url => horse_vote_path(horse)}) do |f|
      = f.label :comment, "Your opinion"
      = f.text_field :comment
      ...
      a bunch of labels and input elements follow generated using the form helpers

This will generate working code but it does generate forms with the same ids for all the form elements which makes the HTML invalid once the votingbox partial is rendered a second time.

My first guess at fixing this was to specify a unique :id to form_for but that only applies to the form tag generated by form_for and not any of the tags inside the form_for block.

One definite solution to this problem is to go through and manually define my own unique ids on form_for and all the form elements I use. This is more work than I had hoped for.

Is there an easier or cleaner way to get unique ids in a similar format to the way Rails currently generates them on all my form elements?

A: 

I have removed the original answer as it is totally irrelevant to the updated version of the question.

Update: So now we know that you have an unsaved ActiveRecord object passed to the form_for call, the answer becomes simple: You can override any parameter that form_for generates. That includes the element id. And fields_for sets the context for a specific record.

= form_for(Vote.new, :url => horse_vote_path(horse), :id => dom_id(horse, 'vote')) do |f|
  = f.fields_for horse, :index => horse do |fh|
    = fh.text_field :whatever
    …
edgerunner
get_vote in this scenario is always going to return `Vote.new` which will be an unsaved ActiveRecord object. I've revised the original question accordingly.What would be ideal here is if I could generate the form ids based on the id of the horse object. In this situation the id for the form would be `vote_new_1` for when that partial is rendered for the Horse object with id 1.
cyberkni
I have updated the answer, please see.
edgerunner
May I suggest: `:id => dom_id(horse, 'vote')` to generetate `horse_123_vote`. It's easier to read.
Ariejan
Thanks, Ariejan. Updated the answer.
edgerunner