Forum: Ruby on Rails many_to_many relationship problem

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.
AntuanB (Guest)
on 2007-01-19 17:31
(Received via mailing list)
Hello everyone, i wonder if someone can help i'm a newcomer and this
problem is driving me crazy.
I have this two models with a habtm relationship Entidad(entity) and
Persona(person), on the people view i want to see the entity/es he
belongs to and viceversa, so far so good.
The thing im getting stuck is with the form that handles the editing to
add more people to an entity, heres what i got (mostly scaffold code
with some additions):

In the controller:

  def edit
    @persona = Persona.find(params[:id])
    @persona_entidad = Persona.find(params[:id]).entidades
    @entidades = Entidad.find(:all, :order => "nombre").map {|u|
[u.nombre, u.id] }
  end

  def update
    @persona = Persona.find(params[:id])
     @persona.entidades << @entidades
     @persona.save
    if @persona.update_attributes(params[:persona])
      flash[:notice] = 'Persona was successfully updated.'
      redirect_to :action => 'show', :id => @persona
    else
      render :action => 'edit'
    end
  end

On the view:

<p><label for="persona_entidad_id">A&ntilde;adir pertenencia a
entidad</label><br/>
<%= select(:entidades_personas, :entidad_id, @entidades ) %></p>


I get th following error:
Entidad expected, got NilClass

The closer i've got to the solution is with this change to the
controller:

  def update
    @persona = Persona.find(params[:id])
     @persona.entidades << Entidad.find(params[:entidad_id])
     @persona.save
    if @persona.update_attributes(params[:persona])
      flash[:notice] = 'Persona was successfully updated.'
      redirect_to :action => 'show', :id => @persona
    else
      render :action => 'edit'
    end
  end

where i get this error:  Couldn't find Entidad without an ID

Basically i want an object of the type Entidad to be added to
Persona.entidad, i can do it with irb but im unable with the rails
models.

Thanks in advance and bye everyone
This topic is locked and can not be replied to.