Search code examples
ruby-on-railsrubyruby-on-rails-2

Rails Association Chains


I have two models, Circuit and Organisation with the following relationship:

circuit.rb

belongs_to :organisation

organisation.rb

has_many :circuits

circuit_controller.rb

...
if params[:id]
  @circuit = Circuit.find(params[:id])
  @backup_circuits = @circuit.organisation.circuits.where('id != ?', @circuit.id)
end
...

update.rhtml (Circuit View)

<%= collection_select 'circuit', 'backup_circuit_id', @backup_circuits, :id, :product_name %>

but I get this error: undefined methodproduct_name' for " # AND id != ? ":String`

As far as I can see the modelling should be fine, the only thing I'm doubtful about is the chaining I have done in the controller as it seems a bit funny to find the circuit, it's organisation and then other circuits belonging to that organisation.

Rails verions is 2.3.14

Alternatively, if I use

<%= select "circuit", "backup_circuit_id", @backup_circuits %>

instead then I the page renders but my dropdown values are empty and the values are the hex address you get when you know something is broken...


Solution

  • I don't think that Rails 2.3.14 supports the .where() - Actually it does not for Rails 2.3.11, just tried it.

    In Rails 2.3.14, you can't really chain the queries... Here is the Rails 2.3.x solution:

    @circuit.organisation.circuits.find(:all, :conditions => ['id != ?', @circuit.id])