I have this attitude to many:
class Programa < ActiveRecord::Base attr_accessible :descripcion, :nombre, :roles_attributes has_many :roles, :dependent => :restrict accepts_nested_attributes_for :roles ... end class Role < ActiveRecord::Base attr_accessible :description, :name, :programa_id belongs_to :programa ... end
It works in the rails console:
> params = { programa: { nombre: 'nuevo', roles_attributes: [ {name: 'role1'}, {name: 'role2'}] }} > p = Programa.create(params[:programa]) > p => #<Programa id: 7, nombre: "nuevo", descripcion: nil, created_at: "2013-10-09 14:07:46", updated_at: "2013-10-09 14:07:46"> > p.roles => [#<Role id: 15, name: "role1", description: nil, created_at: "2013-10-09 14:07:46", updated_at: "2013-10-09 14:07:46", programa_id: 7>, #<Role id: 16, name: "role2", description: nil, created_at: "2013-10-09 14:07:46", updated_at: "2013-10-09 14:07:46", programa_id: 7>]
But I can not get it to work in the application / views / programas / _form:
<%= form_for(@programa) do |f| %> <%= render 'shared/form_error_messages', object: f.object %> <div class="field"> <%= f.label :nombre %> <%= f.text_field :nombre %> </div> <div class="field"> <%= f.label :descripcion %> <%= f.text_field :descripcion %> </div> <% f.fields_for :roles do |builder| %> <div class="field"> <%= builder.label :name %> <%= builder.text_field :name %> </div> <div class="field"> <%= builder.label :description %> <%= builder.text_field :description %> </div> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %>
Is there anything else I have to add or remove in order to make my form that shows the roles of nested attributes?
This is my controller for programs:
class ProgramasController < ApplicationController
I just want nested attributes to appear only in edit and display actions.