Reputation: 7280
I have created a new model in my app - PaypalOrder. Now in one of the methods of this model I want to be able to access current_order
object. Where Order is an existing model. How can I do this in ruby on rails?
I read about associations, but they seem a bit complicated.
EDIT: The problem with using associations is that not every Order will have a corresponding PaypalOrder. But whenever there is a PaypalOrder I want to access Order. How can I setup this association
Upvotes: 0
Views: 75
Reputation: 3435
Hm... current_order and curren_user and usually current_s are tight to the session. So they can be accessed only by the controller. Since the models are handling business-domain logic they shouldn't access these objects...
Upvotes: 0
Reputation: 15838
what about:
class PaypalOrder
belongs_to :order
end
?
you need an "order_id" column in paypal_orders table
and that's it
you then create a PaypalOrder with
def some_action
current_order = Order.find(some_id)
paypal_order = PaypalOrder.new(order: current_order)
#do what you want with paypal_order
end
if you don't have the order_id do
bundle exec rails g migration AddUserToPaypalOrder
and the change method
add_column :paypal_orders, :user, :references
or
add_column :paypal_orders, :user_id, :integer
Upvotes: 1
Reputation: 7078
The way to go is to use concerns, it works like this:
Model:
# app/models/PayPayOrder.rb
class PayPalOrder < BaseModel
# concerns
include MyMultipleNeededMethods
...
def now_i_use_the_concern_method
concern_method
end
...
end
Concern:
# app/models/concerns/MyMultipleNeededMethods.rb
module MyMultipleNeededMethods
extend ActiveSupport::Concern
def concern_method
puts "refactored like a boss"
end
...
end
Never ever try to cross reference methods this way. Use the given rails framework, its awesom ;-)
Upvotes: 0