Topic: Trying to save in two models using one form

Hi all

I have 2 tables. Lesson and Tag. A lesson can have multiple tags. When I save, records are saving in both tables but the tag.body is saving as NULL. What am I doing wrong?

This is lesson,rb
class Lesson < ActiveRecord::Base
#Mandatory fields validation
validates_presence_of :title, :contact_yn
has_many :tags
end

This is tag.rb
class Tag < ActiveRecord::Base
    belongs_to :lesson
end

My lesson.new is
<h1>New lesson</h1>

<%= error_messages_for :lesson %>
<%= error_messages_for :tag %>

<% form_for(@lesson) do |f| %>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </p>
 
  <p>
    Can others contact you?<br />
   <%= f.select :contact_yn, ['Yes', 'No'] %>
  </p>
<% fields_for :tags do |i| %>
      <p>
        Tags:<br />
    <%= i.text_field :body %>
</p>
<% end %>
  <p>
    <%= f.submit 'Save' %>
  </p>
 
<% end %>
<%= link_to 'Back', lessons_path %>

My lesson controller is
def new
    @lesson = Lesson.new
    @tag = Tag.new
   
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @lesson }
    end
  end

  # GET /lessons/1/edit
  def edit
    @lesson = Lesson.find(params[:id])
  end

  # POST /lessons
  # POST /lessons.xml
  def create
    @lesson = Lesson.new(params[:lesson])
    $tag = @lesson.tags.build(params[:tag])

    respond_to do |format|
      if @lesson.save
        flash[:notice] = 'Lesson was successfully created.'
        format.html { redirect_to(@lesson) }
        format.xml  { render :xml => @lesson, :status => :created, :location => @lesson }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @lesson.errors, :status => :unprocessable_entity }
      end
    end
  end


When I save, records are saving in both tables but the tag.body is saving as NULL. What am I doing wrong?

TIA
-vas

Re: Trying to save in two models using one form

accepts_nested_attributes_for

Re: Trying to save in two models using one form

Sorry.. I don't follow. Is that something I should use?

Re: Trying to save in two models using one form

Take a look at the following post smile

http://ryandaigle.com/articles/2009/2/1 … attributes