ruby on rails - Has_many through association not working -


in node model have association below, 2 nodes linked in link model:

has_many :first_links, class_name:  "link",                        foreign_key: "first_node_id" has_many :second_links, class_name:  "link",                         foreign_key: "second_node_id" belongs_to :organization 

i want have links associated node, irrespective whether node first_node or second_node. therefore have method below in node model:

def links   first_links + second_links end 

if try node.first.links in console, works , list of links node, irrespective if node first or second node of link. relationship seems working.

in organization model have:

has_many :nodes has_many :links, through: :nodes, source: :links 

however, organization.first.links in console generates error:

could not find source association(s) "link" or :links in model node.

what doing wrong through association?


update: understand need custom method collect links organization. following made sense me (added organization model):

has_many :nodes def links   nodes.each |node|     self.links ||= []            #create array if doesn't exist yet.     links << node.links.collect  #add links array.   end end 

if try organization.first.links in console, produces error below. idea method should like?

/usr/local/rvm/gems/ruby-2.2.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:282:in `blame_file!': can't modify frozen fatal (runtimeerror)

hmmm..

you can call organization.nodes , not organization.links, since method in node class.

what can try, however, create similar method (which instance method) in organization class, return links nodes belonging instance of organization on newly created method called.

eg:

def links   self.nodes.joins(:first_links) + self.nodes.joins(:second_links) end 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -