Ruby on Rails - pass variable to nested form
- by Krule
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.