Nested routing for models with double associations
In a toy Rails application, I'm modelling a situation where you have a number of pots, each containing an amount of something, and you can make transactions between the pots. A transaction can come from any pot, and go to any pot.
Here are the relevant parts of the models:
class Pot < ActiveRecord::Base
has_many :to_transactions, :foreign_key => "to_id", :class_name => "Transaction"
has_many :from_transactions, :foreign_key => "from_id", :class_name => "Transaction"
end
class Transaction < ActiveRecord::Base
belongs_to :to_pot, :class_name => "Pot", :foreign_key => "to_id"
belongs_to :from_pot, :class_name => "Pot", :foreign_key => "from_id"
end
This allows me to do the following at the console:
>> p = Pot.find(123)
>> p.from_transactions
=> # returns array of transactions from pot 123
>> t = p.to_transactions.new
=>开发者_如何学运维 # t is a new transaction with to_id set to 123
and so on.
I'm having a problem setting up the routing. For example, I would like:
/pots/123/from_transactions
to give a list of all transactions from pot 123,/pots/123/to_transactions/new
to give the new transaction form, with theto_id
set to 123
Is this possible? Any help gratefully received etc etc.
I would say a clean way of managing is that all the from_transactions related request go to from_transactions_controller and to_transactions related go to to_transactions_controller. But the underlying model could be same for both:
In routing file you could specify your routes as follows:
'pots/:id/to_transactions/new', :controller => 'to_transactions', :action => 'new'
'pots/:id/from_transactions/', :controller => 'from_transactions', :action => 'index'
Does that help?
My routes.rb now includes the following:
map.resources :transactions, :path_prefix => '/pots/:from_id', :as => :from_transactions
map.resources :transactions, :path_prefix => '/pots/:to_id', :as => :to_transactions
This means, for example, that a request to /pots/123/from_transactions/new
is sent to the transactions
controller, and params[:from_id]
is set to 123.
精彩评论