Ruby on Rails - pass variable to nested form

Posted by Krule on Stack Overflow See other posts from Stack Overflow or by Krule
Published on 2010-05-25T19:02:44Z Indexed on 2010/05/31 15:23 UTC
Read the original article Hit count: 183

Filed under:

I am trying to build a multilingual site using Rails, but I can't figure out how to pass variable to nested form.

Right now I am creating nested form like this.

@languages.each do
  @article.article_locale.build(:language_id => language.id)
end

But i would like to pass value of language to it so i can distinguish fields. Something like this.

@languages.each do |language|
  @language = language
  @article.article_locale.build(:language_id => language.id)
end

However, I always end up with language of the last loop iteration.

Any way to pass this variable?


-- edit --

In the end, since I've got no answer I have solved this problem so it, at least, works as it should. Following code is my partial solution.

In model:

def self.languages
  Language.all
end

def self.language_name
  language = []
  self.languages.each_with_index do |lang, i|
    language[i] = lang.longname
  end
  return language
end

In Controller:

def new
  @article = Article.new
  Article.languages.each do |language|
    @article.article_locale.build(:language_id => language.id)
  end
end

In HAML View:

-count = 0
-f.fields_for :article_locale do |al|
  %h3= Article.language_name[count]
  -count+=1
  -field_set_tag do
    %p
      =al.label :name, t(:name)
      =al.text_field :name
    %p
      =al.label :description, t(:description)
      =al.text_area :description 
    =al.hidden_field :language_id

It's not the most elegant solution I suppose, but it works. I would really love if I could get rid of counter in view for instance.

© Stack Overflow or respective owner

Related posts about ruby-on-rails