ruby on rails - Calling models from other models -
two models in rails 4 app - accommodation.rb , account.rb - each accommodation has_one account.
in accommodation.rb have method:
def my_method self.field = "something" save! end and call method accommodationscontroller.rb using:
accommodation.my_method but need able call method in account.rb accommodation.rb model whilst maintaining association if create or update record in accounts table know accommodation_id reference. on lines of:
account.accommodation.my_other_method but know won't work "stab in dark"
note i'm trying keep logic in models
to reference associated model (in order call methods on it, instance), use automatically generated method matches name of model.
for instance, if accommodation has_one account, , accommodation accommodation object, can call accommodation.account refer associated account. reference can have methods called on normal: accommodation.account.my_account_instance_method(foo)
alternatively, if you're in method definition in accommodation, can refer method directly:
class accommodation has_one :account def do_something account.my_account_instance_method end end all of pretty documented in rails associations basics guide, highly recommend through @ least briefly.
Comments
Post a Comment