Note that there are some explanatory texts on larger screens.

plurals
  1. POMassaging a mongoid habtm with a string for a class
    primarykey
    data
    text
    <p>I started off with <a href="https://gist.github.com/scttnlsn/1295485" rel="nofollow">https://gist.github.com/scttnlsn/1295485</a> as a basis to make a restful sinatra app. I'm having difficulty, though, managing HaBTM relationships for paths such as</p> <p><code>delete '/:objecttype/:objid/:habtm_type/:habtm_id'</code></p> <p>I already have the objecttype thanks to the map (as per that gist), and pulling the right object from the db with the id is straightfoward. However, getting the other side of the habtm and calling the appropriate method on objecttype to delete the relationship involves turning a handful of strings into the appropriate objects and methods.</p> <p>I came up with a solution, but it uses eval. I'm aware that using eval is evil and doing so will rot my very soul. Is there a better way to handle this, or should I put in some safeguards to protect the code and call it a day?</p> <p>Here's a working, self contained, sinatra-free example to show how I'm doing the eval:</p> <pre><code>require 'mongoid' require 'pp' def go seed frank = Person.find_by(name:"Frank") apt = Appointment.find_by(name:"Arbor day") pp frank really_a_sinatra_route(frank.id, "appointments", apt.id) frank.reload pp frank end def really_a_sinatra_route(id, rel_type,rel_id) # I use "model" in the actual app, but hardwired a person here to # make a simpler example person = Person.find_by(id: id) person.deassociate(rel_type,rel_id) end class Base def deassociate(relationship,did) objname = associations[relationship].class_name # Here's the real question... this scares me as dangerous. Is there # a safer way to do this? obj = eval "#{objname}.find(did)" eval "#{relationship}.delete(obj)" end end class Person &lt; Base include Mongoid::Document has_and_belongs_to_many :appointments end class Appointment &lt; Base include Mongoid::Document has_and_belongs_to_many :persons end def seed Mongoid.configure do |config| config.connect_to("test_habtmexample") end Mongoid.purge! frank=Person.create(name:"Frank") joe=Person.create(name:"Joe") ccon = Appointment.create(name:"Comicon") aday = Appointment.create(name:"Arbor day") frank.appointments &lt;&lt; ccon frank.appointments &lt;&lt; aday ccon.persons &lt;&lt; joe joe.reload end go </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload