A
A
Alexander Zolotov2015-03-16 07:19:18
Ruby on Rails
Alexander Zolotov, 2015-03-16 07:19:18

How to extend the has_and_belongs_to_many and has_many associations to assign a function to a single model object?

class Product < ActiveRecord::Base
   has_and_belongs_to_many :specs do
      		def test
               p 'Hello!'
   		   end
   	end
end

This Product.last.specs.testwill return 'Hello!'
And how to do it:
specs.each do |spec_one| 
   spec_one.test
end
to assign a function to a single Spec model object? (i.e. so that spec s [0].test outputs 'Hello!')

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bmalets, 2015-03-31
@bmalets

just add your method:

def test
    p 'Hello!'
end

to your model Spec
By the way, you can't call the model like that - there may be problems with tests if you use Rspec.
I do not advise you to try to program in ruby ​​until you have read a book about ruby ​​and a guide on rails.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question