Forum: Ruby on Rails THREE MODELS PROBLEM IN 'NEW' ACTION

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D3c70fc3354bb2fde5b3c85d9c9442a3?d=identicon&s=25 Jose G. (Guest)
on 2009-02-13 08:51
(Received via mailing list)
Hello,

I have this problem :

When I use three models, and associate them, then, my 'new' action need
more data to work, How can I resolv it, or I do it in the right way ?

Thanks

Jose.


******************** my models *************************

class Libro < ActiveRecord::Base
  has_many :lecciones
end

class Leccion < ActiveRecord::Base
  has_many :vocabularios
  belongs_to :libro
end

class Vocabulario < ActiveRecord::Base
  belongs_to :leccion
  belongs_to :libro
end

**************** routes.rb ****************************

ActionController::Routing::Routes.draw do |map|
  map.resources :vocabularios

  map.resources :lecciones

  map.resources :libros

  map.resources :libros, :has_many => :lecciones

  map.resources :libros do |libro|
     libro.resources :lecciones do |leccion|
       leccion.resources :vocabularios
     end
  end

  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:id.:format'
end

*************** my controllers *****************************

class VocabulariosController < ApplicationController

  def new
    @libro = Libro.find(params[:libro_id])
    @leccion = @libro.lecciones.find(params[:leccion_id])
    @vocabulario = @leccion.vocabularios.build(params[:vocabulario])

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @vocabulario }
    end
  end

  def create
    @libro = Libro.find(params[:libro_id])
    @leccion = @libro.lecciones.find(params[:leccion_id])
    @vocabulario = @leccion.vocabularios.build(params[:vocabulario])

    # Here '@vocabulario' never have 'libro' and write in the
    # database 'NULL'
    # why it never works ?

    # i need to put something like :

    # @vocabulario.libro = @libro

    # then the insert in database works fine, WHY ?
    # is this ok ?

    if @vocabulario.save
      redirect_to libro_leccion_vocabulario_url(@libro, @leccion,
@vocabulario)
    else
      render :action => "new"
    end

  end

end
This topic is locked and can not be replied to.