I have two models, Curso and Ementa
class Curso < ActiveRecord::Base
attr_accessible :nome, :descricao, :periodo_inscricao_inicio,
:periodo_inscricao_fim
has_one :ementa, :dependent => :destroy
has_many :turmas
has_many :publico_alvos
accepts_nested_attributes_for :ementa
end
class Ementa < ActiveRecord::Base
belongs_to :curso
end
One form for hadle both models
<% form_for @curso do |f| %>
<%= f.error_messages %>
<%= f.label :nome %>
<br/>
<%= f.text_field :nome %>
<%= f.label :descricao %>
<br/>
<%= f.text_area :descricao %>
<%= f.label :periodo_inscricao_inicio %>
<br/>
<%= f.date_select :periodo_inscricao_inicio %>
<% fields_for :ementa do |ementa_form| %>
<%= ementa_form.label :descricao, “Ementa” %>
<%= ementa_form.text_field :descricao %>
<% end %>
<%= f.label :periodo_inscricao_fim %>
<br/>
<%= f.date_select :periodo_inscricao_fim %>
<%= f.submit "Submit" %>
<% end %>
the controller
class CursosController < ApplicationController
def index
@cursos = Curso.all
end
def show
@curso = Curso.find(params[:id])
respond_to do |format|
format.html {render :layout=>false}
end
end
def new
@curso = Curso.new
@curso.build_ementa
respond_to do |format|
format.html {render :layout=>false}
end
end
def create
@curso = Curso.new(params[:curso])
if @curso.save
flash[:notice] = "Successfully created curso."
redirect_to @curso
else
render :action => 'new'
end
end
def edit
@curso = Curso.find(params[:id])
respond_to do |format|
format.html {render :layout=>false}
end
end
def update
@curso = Curso.find(params[:id])
if @curso.update_attributes(params[:curso])
flash[:notice] = "Successfully updated curso."
redirect_to @curso
else
render :action => 'edit'
end
end
def destroy
@curso = Curso.find(params[:id])
@curso.destroy
flash[:notice] = "Successfully destroyed curso."
redirect_to cursos_url
end
end
The result is just one insert on curso table, why it is not inserting on
ementa table to the “descricao” field?
Console result:
Processing CursosController#create (for 127.0.0.1 at 2010-03-01
00:46:32)
[POST]
Parameters:
{“authenticity_token”=>“aZzxtPN1y4nOWB3GwAAWSqGfU1iEPIiL2+rbEjjIr3k=”,
“curso”=>{“nome”=>“Test”, “descricao”=>“test”,
“periodo_inscricao_inicio(3i)”=>“1”, “periodo_inscricao_inicio(2i)”=>“3”,
“periodo_inscricao_inicio(1i)”=>“2010”, “periodo_inscricao_fim(3i)”=>“1”,
“periodo_inscricao_fim(2i)”=>“3”, “periodo_inscricao_fim(1i)”=>“2010”},
“ementa”=>{“descricao”=>“test”}, “commit”=>“Submit”}
[4;36;1mSQL (1.0ms) [0m [0;1mBEGIN [0m
[4;35;1mSQL (2.0ms) [0m [0mINSERT INTO “cursos” (“nome”,
“descricao”,
“periodo_inscricao_inicio”, “periodo_inscricao_fim”, “created_at”,
“updated_at”) VALUES(E’Test’, E’test’, ‘2010-03-01’, ‘2010-03-01’,
‘2010-03-01 03:46:32.756995’, ‘2010-03-01 03:46:32.756995’) RETURNING
“id” [0m
[4;36;1mSQL (2.0ms) [0m [0;1mCOMMIT [0m
–
Ramon de Paula Marques
Estudante de Engenharia de Computação - UFG