ruby-on-railserbfields-for

How to generate Rails form dynamically dependant on languages


I have a form and I want to show some form elements x times dependent on languages in Langs table, it is nested attributes with has_many association. I am trying to use fields_for but with no success.

I have a Lang objects and this code in template.

  <%= fields_for :categories_versions, @langs do |lang| %>
    <div class="card mt-4 mb-4">
      <div class="card-body">
        <div class="container mt-4">
          <%= "Category for #{Lang.find(lang.id).lang}" %><br/>

it yields ActionView object, but I want to access every lang in @langs (which is simply Lang.all.

And it generates me just one set, but I have 2 languages, so my desired output is form with 2 sets of columns for every of two languages with name of the language.

What am I doing wrong?


Solution

  • The object that is given to you by fields_for (namely the |lang| in your example) is a form helper, not an object from the @lang collection. So to get the id of current lang you would need to do lang.object.id. I'd suggest you change |lang| to |lang_f| to avoid confusion. Also if @langs is not of the same type as :categories_versions, I am not sure this is going to work properly. You probably want something like:

    <% @langs.each do |lang| %>
      <%= fields_for :categories_versions do |version_f| %>    
        <%= "Category for #{lang.name}" %><br/>
    
        <%# You will probably want to associate the category version with the lang. %>
        <%# Maybe like this. Depends on how you set it up %>
        <%= version_f.hidden_field :lang_id, lang.id %>
        ...
      <% end %>
    <% end %>
    

    I am making some assumptions here, so adjust to your actual attributes and models.