1

Is there a way to have a couple generic lines of code that can return results from the correct model_class based on the the model definition, and not on the lines of code?

Right now, I'm using a generator to create:

<%= f.collection_select(:semanticZoomOut, Class.all.sort { |a,b| a.name <=> b.name },
  :id, :name, options = {
    :prompt => "Please Select an Item",
    :selected => @instance.semanticZoomOut.map(&:id)
  }, html_options = {:multiple => true, :class=>"search"}) %>

Where "Class" has to be manually changed for each _form.html.erb. Preferably, I'd like to generate something like this:

<%= f.collection_select(:semanticZoomOut, @instance.semanticZoomOut.class.all.sort { |a,b| a.name <=> b.name },
  :id, :name, options = {
    :prompt => "Please Select an Item",
    :selected => @instance.semanticZoomOut.pluck(id)
  }, 
  html_options = {:multiple => true, :class=>"search"}) %>
joshfindit
  • 611
  • 6
  • 27

1 Answers1

1

How about this?

clazz = @instance.class.associations[:semanticZoomOut].model_class.to_s.constantize
clazz.all.sort_by(&:name)

Or if you want to let Cypher do the work:

clazz.order(:name)
Brian Underwood
  • 10,746
  • 1
  • 22
  • 34
  • If I'm not mistaken. that would give the class of the instance, not it's related node. – joshfindit Jul 20 '16 at 00:33
  • `@instance.class` gives you the class and then calling methods like `all`, `order`, `where`, etc... will give you a scoped representation of nodes for that class. What do you mean by "related node"? – Brian Underwood Jul 20 '16 at 13:11
  • What I mean by related node is that if I have a `has_many` relationship on `(instance)-[:SEMANTIC_ZOOM_OUT]->(zoomedOutObject)`, and each has a different class, then what I want is the class of the "related node" `zoomedOutObject`, not the class of `instance`. – joshfindit Jul 21 '16 at 18:03
  • (p.s. Thanks for the tip on sorting) – joshfindit Jul 21 '16 at 22:36
  • Oh, yeah, duh ;) You can reflect on the associations by calling the `associations` method on a class and each association will have a `model_class` method. See my updated answer – Brian Underwood Jul 22 '16 at 18:17
  • That seems to get very close, returning the right Class name, but doing `clazz.all` gets `undefined method 'all' for :ZoomedOutObject:Symbol` – joshfindit Jul 23 '16 at 13:55
  • Ah, right, I thought that would be a class constant. You'll probably need `to_s.constantize` on the end (just updated the answer) – Brian Underwood Jul 24 '16 at 15:24