I have a Shipment class that is used to ship packages between Branches.
However, when I try to have two belongs_to in Shipment called shipped_to
and shipped_from I can’t seem to make it work. I can get it to display
the form properly but when I select the branches and click save I get
the following error…
“Branch expected, got String”
Any ideas? I have added some code snipplets below for reference.
Thanks!
shipment.rb:
class Shipment < ActiveRecord::Base
belongs_to :shipped_to,
:class_name => ‘Branch’,
:foreign_key => ‘shipped_to_id’
belongs_to :shipped_from,
:class_name => ‘Branch’,
:foreign_key => ‘shipped_from_id’
end
branch.rb
class Branch < Entity
has_many :shipped_to,
:class_name => ‘Shipment’,
:order => ‘updated_on DESC’,
:foreign_key => ‘shipped_to_id’,
:dependent => true
has_many :shipped_from,
:class_name => ‘Shipment’,
:order => ‘updated_on DESC’,
:foreign_key => ‘shipped_from_id’,
:dependent => true
end
entity.rb
class Entity < ActiveRecord::Base
end
_form.rhtml:
<%= error_messages_for ‘shipment’ %>
Shipped to | <%= collection_select 'shipment', 'shipped_to', @branches, 'id', 'name' %> |
---|---|
Shipped from | <%= collection_select 'shipment', 'shipped_from', @branches, 'id', 'name' %> |
shipments_controller.rb:
class ShipmentsController < ApplicationController
def new
@branches = Branch.find(:all, :order => ‘name’)
case request.method
when :get
@shipment = Shipment.new
when :post
@shipment = Shipment.new(params[:shipment])
if @shipment.save
flash[:notice] = ‘Shipment was successfully created’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end
end
end