lets say I have a table call payment that have a field call thing_id that will be the foreign key of buy and storage depend on the thing_type field in payment table.
How do I implement this relationship? In migration file , how do I define the foreign key?
In model file , I should use :through ?
I am not sure, but I think you are talking about Polymorphic associations in Rails.
Have a look here: Railscasts – Polymorphic Association