Search code examples
ruby-on-railshas-manybelongs-to

Problems saving ids in belongs_to relationship


I have 3 objects: users, travels, points.

A user has many travels, a travel has many points, a point belongs to one travel e one user.

A travel has also a boolean attribute (:open) which tells if is it in curse or not.

The problem is that I can't save "travel_id" of the current travel in my points table.

Here is the code:

class Point < ActiveRecord::Base
    belongs_to :travel, :foreign_key=> "travel_id"
    belongs_to :user, :foreign_key=> "user_id"
end


class Travel < ActiveRecord::Base
    has_one :user, :foreign_key => "user_id"
    has_many :ways
    has_many :points
    attr_accessible :description, :start_date, :last_date
    validates_date :last_date, :on_or_after => :start_date
end

Points controller:

...
 def create
   @point = Point.new(params[:point])
   @point.user_id = current_user.id
   @travel = current_user.travels.find(:all, :conditions => {:open => true})
   @point.travel_id = @travel.id
   respond_to do |format|
     if @point.save
       format.html { redirect_to(@point, :notice => 'Point was successfully created.') }
       format.xml  { render :xml => @point, :status => :created, :location => @point }
     else
       format.html { render :action => "new" }
       format.xml  { render :xml => @point.errors, :status => :unprocessable_entity }
     end
   end
 end
...

Every time I try to save a new point, @point.travel_id = -614747648


Solution

  • A few things could do with being fixed up here.

    Firstly, you don't need to specify :foreign_key when the key is just the same as the relation name + _id.

    Second, you don't need to (and generally shouldn't) set the foo_id fields directly; it's more usual to do @point.user = current_user.

    Thirdly, and the direct cause of your problem, is that @travel has been set to the result of a find(:all, ...) call - so it's an Array of Travel objects. What you're saving into @point.travel_id will be Ruby's internal id for the @travel Array, rather than a database ID for a single row.