Ruby: undefined method `delete', deleting parent and child data at the same time - ruby

I'm a newbie programmer, basically I'm trying to delete a record from a database table, however this record would be used on a child table with a composed primary key taking both from different tables.
This is the class of the table I need to delete the child data from.
class Detalle_Mapa
include DataMapper::Resource
storage_names[:default] = 'detalle_ma'
property :clave_mapa, String, :length => 2, :required => true, :key => true
property :clave_asig, String, :length => 10, :required => true, :key => true
property :clave_cuatri, String, :length => 2, :required => true
belongs_to :mapa_curricular, 'Mapa_Curricular', :child_key => [:clave_mapa], :key => true
belongs_to :cuatrimestre, 'Cuatrimestre', :child_key => [:clave_cuatri], :key => true
belongs_to :asignatura, 'Asignatura', :child_key => [:clave_asig]
end
So now when I try to delete data from the parent table, it won't delete it since the PK is being used on the child table for other data. If this was normal SQL sintax it wouldn't be a big deal but I'm having a hard time finding a way around it on Ruby.
This is the basic method that works when deleting data that's not being used as a FK.
delete '/deleteMapCurricular/:clave_mapa' do
#mapa = Mapa_Curricular.get(params[:clave_mapa])
if #mapa
#mapa.destroy
redirect '/catMapCurricular'
end
end
And this is one of the ways I've tried to delete the child data, which is clearly not right...
Detalle_Mapa.where(:clave_mapa => [params[:clave_mapa]]).delete_all
Is there an easy way to just delete a bunch of data from a database that I'm not aware of? Or what I'm I not getting about this ActiveRecords on Ruby?
I'm sorry if the question is ambiguous or if I'm not explaining myself clearly, I usually find everything on forums and there is no need to ask myself. Any help will be greatly appreciated :)

Sorry for not giving out the exact answer. But I can tell a concept in this answer
class User < ActiveRecord::Base
has_many :fruits, dependent: :destroy
end
class Fruit < ActiveRecord::Base
belongs_to :user
end
So in the above example, if you delete a user, the associated fruits for that user will also be deleted automatically.

Related

Unable to destroy a parent object

I have a large and complicated User model that looks something like this:
class User
class Link
include DataMapper::Resource
property :id, Serial, :key => false
belongs_to :follower, :model => 'User', :key => true
belongs_to :followed, :model => 'User', :key => true
end
include DataMapper::Resource
property :id, Serial
property :username, String, :required => true
has n, :links_to_followers, :model => 'User::Link', :child_key => [:followed_id]
has n, :links_to_followed, :model => 'User::Link', :child_key => [:follower_id]
has n, :comments
has 1, :profile_image
end
My problem is that Datamapper is not letting me Destroy it. I thought this was a result of Datamapper not wanting to destroy an object with un-destroyed child objects so I put in a method destroy_deep that calls destroy on the links_to_followers, links_to_followed, underlying comments, and the profile image (these are all destroyed correctly).
However, even if I call user.destroy after that, the user is not destroyed. There are no error messages of any kind. Is there some kind of cascading delete command that I am missing?
I resolved this.
Apparently to debug destroy, object.errors isn't useful. Instead track exceptions like:
begin
u.destroy
rescue Exception => e
p e
end
The solution was that one of the children fields didn't map back to User. I had a class Like that belonged to User, but User didn't have n Likes.

Querying and sorting embedded document in mongoid

I have three classes
class Post
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user, :inverse_of => nil
embeds_many :comments, :as => :commentable
field :content, :type => String
end
class Commment
include Mongoid::Document
include Mongoid::Timestamps
belongs_to :user, :inverse_of => nil
embedded_in :commentable, :polymoriphic => true
end
class User
has_many :posts, :dependent => :destroy
field :name, :type => String
end
Whenever the user creates a new comment, I want to compare the contents of it with the latest comment that the user has made. Here is my code that fetches the latest comment by the user:
comments_user=[]
Post.where("comments.user_id" => user.id).
only(:comments).
each {|p| comments_user += p.comments.where(:user_id => user.id).to_a}
latest_comment = comments_user.sort_by{|comment| comment[:updated_at]}.reverse.first
The above code gives me the result but the approach taken is not efficient as I have to traverse through all the posts that the user has commmented to find the latest comment. If any, can anyone provide me a more efficient solution to this problem?
Simply speaking, Isn't there any way I can get all the comments made by this user?
This should fetch the latest user`s comment:
Post.where("comments.user_id" => user.id).order_by(:'comments.updated_at'.desc).limit(1).only(:comments).first
This is standard problem with embedding. It greatly improves some queries ("load post with all its comments"), but makes others non-efficient/impractical ("find latest comment of a user").
I see two options here:
Keep embedding and duplicate data. That is, when user makes a comment, embed this comment to a post document and to the user document. This data duplication has its drawbacks, of course (what if you need to edit comments?);
Stop embedding and start referencing. This means that comment is now a top level entity. You can't quickly load a post with comments, because there are no joins. But other queries are faster now, and there's no data duplication.

MongoMapper: how do I create a model like this

Suppose we have two models, Task and User.
So a user can have many tasks and tasks should be able to have many users too. But, a task should also have a unique creator who is also a user.
Exemple:
A task in this context is like this:
Task ID, Task Creator, Users who should do the task
User_1 creates a task and he is then the creator.
User_1 specifies User_2 and User_3 as users who should do the task. So these two last users are not creators of task.
How do I create this models so that if I have a task object, I can find it's creator and users who should complete it. And how do I do, if I have a user, to find all tasks he created and all tasks he should complete.
You'll need a many-to-many relationship between the Tasks and Users, and you need an additional one-to-many relationship between Users and Tasks, pointing to the creator (User).
Something along these lines: (I usually use Mongoid, so double-check the syntax for the relations in the MongoMapper API - link below.. you might to manually specify :foreign_key and :class)
The idea is that you have two relationships between the models, one which models the many-to-many relationship
with which you get either to the assigned_users or assigned_tasks, and a one-to-many relationship with which you get to either the creator of a task, or the created_tasks for a given user. If you chose these names for the relationships, it will be clear which is which.
class Task
include MongoMapper::Document
key :title, String , :required => true
key :user_ids , Array
has_many :users, :in => user_ids # , :as => :assigned_users
key :creator_id , ObjectId
belongs_to: user, :as => :creator
end
class User
include MongoMapper::Document
key: name, String, :required => true
has_many :tasks # , :as => :assigned_tasks
has_many :tasks, :as => :created_tasks
end
See:
http://mongomapper.com/documentation/plugins/associations.html
The answer suggested by Tilo is correct about how to model the data, but the example code is incorrect and will not work. The :as option is for polymorphic associations, you want to use the :foreign_key option. Also, you can't have two associations named the same. See below for revised code.
class Task
include MongoMapper::Document
key :title, String , :required => true
key :assigned_user_ids, Array
has_many :assigned_users, :in => :assigned_user_ids
key :creator_id , ObjectId
belongs_to :creator, :class => User
# userstamps! also accomplishes the above
end
class User
include MongoMapper::Document
key: name, String, :required => true
has_many :created_tasks, :foreign_key => :creator_id, :class => Task
# inverse of many :in is still in the works
# see https://github.com/jnunemaker/mongomapper/pull/259
# this is a decent workaround for now
def assigned_tasks
Task.where(:assigned_user_ids => self.id)
end
end
See also:
MongoMapper userstamps! documentation

DataMapper filter records by association count

With the following model, I'm looking for an efficient and straightforward way to return all of the Tasks that have 0 parent tasks (the top-level tasks, essentially). I'll eventually want to return things like 0 child tasks as well, so a general solution would be great. Is this possible using existing DataMapper functionality, or will I need to define a method to filter the results manually?
class Task
include DataMapper::Resource
property :id, Serial
property :name , String, :required => true
#Any link of type parent where this task is the target, represents a parent of this task
has n, :links_to_parents, 'Task::Link', :child_key => [ :target_id ], :type => 'Parent'
#Any link of type parent where this task is the source, represents a child of this task
has n, :links_to_children, 'Task::Link', :child_key => [ :source_id ], :type => 'Parent'
has n, :parents, self,
:through => :links_to_parents,
:via => :source
has n, :children, self,
:through => :links_to_children,
:via => :target
def add_parent(parent)
parents.concat(Array(parent))
save
self
end
def add_child(child)
children.concat(Array(child))
save
self
end
class Link
include DataMapper::Resource
storage_names[:default] = 'task_links'
belongs_to :source, 'Task', :key => true
belongs_to :target, 'Task', :key => true
property :type, String
end
end
I would like to be able to define a shared method on the Task class like:
def self.without_parents
#Code to return collection here
end
Thanks!
DataMapper falls down in these scenarios, since effectively what you're looking for is the LEFT JOIN query where everything on the right is NULL.
SELECT tasks.* FROM tasks LEFT JOIN parents_tasks ON parents_tasks.task_id = task.id WHERE parents_tasks.task_id IS NULL
You parents/children situation makes no different here, since they are both n:n mappings.
The most efficient you'll get with DataMapper alone (at least in version 1.x) is:
Task.all(:parents => nil)
Which will execute two queries. The first being a relatively simple SELECT from the n:n pivot table (WHERE task_id NOT NULL), and the second being a gigantic NOT IN for all of the id's returned in the first query... which is ultimately not what you're looking for.
I think you're going to have to write the SQL yourself unfortunately ;)
EDIT | https://github.com/datamapper/dm-ar-finders and it's find_by_sql method may be of interest. If field name abstraction is important to you, you can reference things like Model.storage_name and Model.some_property.field in your SQL.

activerecord validation - validates_associated

I'm unclear on what this method actually does or when to use it.
Lets say I have these models:
Person < ...
# id, name
has_many :phone_numbers
end
PhoneNumber < ...
# id, number
belongs_to :person
validates_length_of :number, :in => 9..12
end
When I create phone numbers for a person like this:
#person = Person.find(1)
#person.phone_numbers.build(:number => "123456")
#person.phone_numbers.build(:number => "12346789012")
#person.save
The save fails because the first number wasn't valid. This is a good thing, to me. But what I don't understand is if its already validating the associated records what is the function validates_associated?
You can do has_many :phone_numbers, validate: false and the validation you're seeing wouldn't happen.
Why use validates_associated then? You might want to do validates_associated :phone_numbers, on: :create and skip validation on update (e.g. if there was already bad data in your db and you didn't want to hassle existing users about it).
There are other scenarios. has_one according to docs is validate: false by default. So you need validates_associated to change that.

Resources