MongoDB mongoid self reference relationship - mongodb

I am new to mongo/mongoid and I am trying to setup a self referencing relationships on my sites table.
# sites model
has_many :child_sites, :class_name => 'Site'
belongs_to :parent, :class_name => 'Site'
#controller
#event = current_site.child_sites.build(params[:site])
current_site is a function that returns the current site object.
I get this error -
undefined method `entries' for #

You can try changing your relation definitions to the following:
has_many :child_sites, :class_name => 'Site', :cyclic => true
belongs_to :parent_site, :class_name => 'Site', :cyclic => true
I don't know exactly what it does, but I remember it being discussed in the Mongoid google group. If that doesn't work, you should try to set inverse_of on both the relation macros. Most of the time setting inverse_of correctly does the job.
has_many :child_sites, :class_name => 'Site', :inverse_of => :parent_site
belongs_to :parent_site, :class_name => 'Site', :inverse_of => :child_sites
About the extra queries, yes there would be extra queries whenever you want to fetch child_sites of a site or the parent site of a site.
You should consider embedding child sites in parent site, but keep in mind that way you would loose the ability to query child sites in a stand_alone manner. You would always have to access any child site as "parent_site > child_sites".
Also keep in mind the 16MB limit on size of document, which is hard to reach, but might be possible if there are a lot of child sites for a parent and if you are storing template info, like html, css etc. in the document itself.

Cyclic was originally implemented for embedded documents (see user group entry). To make this working on mongoid 2.3 or higher you have to remove the cyclic option:
has_many :child_sites, :class_name => 'Site'
belongs_to :parent_site, :class_name => 'Site'

Can't you use recursively_embeds_many or recursively_embeds_one? http://mongoid.org/en/mongoid/docs/relations.html#common

Related

Fetching Zend Framework URL parameters

I'm building my first Zend Framework application and I want to find out the best way to fetch user parameters from the URL.
I have some controllers which have index, add, edit and delete action methods. The index action can take a page parameter and the edit and delete actions can take an id parameter.
Examples
http://example.com/somecontroller/index/page/1
http://example.com/someController/edit/id/1
http://example.com/otherController/delete/id/1
Until now I fetched these parameters in the action methods as so:
class somecontroller extends Zend_Controller_Action
{
public function indexAction()
{
$page = $this->getRequest->getParam('page');
}
}
However, a colleague told me of a more elegant solution using Zend_Controller_Router_Rewrite as follows:
$router = Zend_Controller_Front::getInstance()->getRouter();
$route = new Zend_Controller_Router_Route(
'somecontroller/index/:page',
array(
'controller' => 'somecontroller',
'action' => 'index'
),
array(
'page' => '\d+'
)
);
$router->addRoute($route);
This would mean that for every controller I would need to add at least three routes:
one for the "index" action with a :page parameter
one for the "edit" action with an :id parameter
one for the "delete" action with an :id parameter
See the code below as an example. These are the routes for only 3 basic action methods of one controller, imagine having 10 or more controllers... I can't imagine this to be the best solution. The only benefit that i see is that the parameter keys are named and can therefore be omitted from the URL (somecontroller/index/page/1 becomes somecontroller/index/1)
// Route for somecontroller::indexAction()
$route = new Zend_Controller_Router_Route(
'somecontroller/index/:page',
array(
'controller' => 'somecontroller',
'action' => 'index'
),
array(
'page' => '\d+'
)
);
$router->addRoute($route);
// Route for somecontroller::editAction()
$route = new Zend_Controller_Router_Route(
'somecontroller/edit/:id',
array(
'controller' => 'somecontroller',
'action' => 'edit'
),
array(
'id' => '\d+'
)
$router->addRoute($route);
// Route for somecontroller::deleteAction()
$route = new Zend_Controller_Router_Route(
'somecontroller/delete/:id',
array(
'controller' => 'somecontroller',
'action' => 'delete'
),
array(
'id' => '\d+'
)
$router->addRoute($route);
I tend to look at it this way:
Determine processing requirements.
What does each "action" need? An edit action and a delete action probably require an :id param. An add action and a list action probably do not. These controllers/actions then consume the params and do the processing.
Note: You can write these comtrollers/actions without any reference to the urls that bring visitors there. The actions simply expect that their params will be delivered to them.
Decide (!) what url's you want.
In general, I find the the (/:module/):controller/:action part of the url largely works fine (except for top-level relatively-static pages like /about, where I often put the actions on an IndexController (or a StaticController) and resent having to include the /index prefix in the url.
So, to handle posts, you might want urls like:
/post - list all posts, probably with some paging
/post/:id - display a specific post
/post/:id/edit - edit a specific post
/post/:id/delete - delete a specific post
/post/add - add a post
Alternatively, you might want:
/post/list - list all posts, probably with some paging
/post/display/:id - display a specific post
/post/edit/:id - edit a specific post
/post/delete/:id - delete a specific post
/post/add - add a post
Or any other url scheme. The point is, you decide the url's you want to expose.
Create routes...
...that map those urls to controllers/actions. [And make sure that whenever you render them, you use the url() view-helper with the route-name, so that a routing change requires no changes to your downstream code in your actions or views.
Do you end up writing more routes this way? Yeah, I find that I do. But, for me, the benefit is that I get to decide on my urls. I'm not stuck with the Zend defaults.
But, as with most things, YMMV.
It all depends on your exact requirements. If you simply want to pass one or two params, the first method will be the easiest. It is not practical to define route for every action. A few scenarios where you would want to define routes would be:
Long urls - If the parameter list for a particular action is very long, you might want to define a route so that you can omit the keys from the request and hence shorten the url.
Fancy urls - If you want to deviate from the normal controller/action url pattern of the Zend Framework, and define a different url pattern for your application (eg, ends with ".html")
Slugs / SEO friendly URLs
To take the example of a blog, you might want to define routes for blog posts urls so that the url is SEO friendly. At the same time, you may want to retain the edit / delete / post comment etc urls to remain the ZF default and use $this->getRequest->getParam() to access the request parameters in that context.
To sum up, an elegant solution will be a combination of routes and the default url patterns.
In a previous answer #janenz00 mentioned "long urls" as one of the reasons for using routes:
Long urls - If the parameter list for a particular action is very long, you might want to define a route so that you can omit the keys from the request and hence shorten the url.
Let's say we have an employee controller with an index action that shows a table of employees with some additional data (such as age, department...) for each employee. The index action can take the following parameters:
a page parameter (required)
a sortby parameter (optional) which takes one column name to sort by (eg age)
a dept parameter (optional) which takes a name of a department and only shows the employees that are working in that department
We add the following route. Notice that when using this route, we cannot specify a dept parameter without specifying a sortby parameter first.
$route = new Zend_Controller_Router_Route(
'employee/index/:page/:sortby/:dept',
array(
'controller' => 'employee',
'action' => 'index')
);
If we would fetch these parameters in our action methods instead, we could avoid this problem (because the parameter keys are specified in the url):
http://example.com/employee/index/page/1/dept/staff
I might be looking at it the wrong way (or might not see the full potential of routing), but to me the only two reasons for using routes are:
If your urls don't conform to the traditional /module/controller/action pattern
If you want to make your urls more SEO-friendly
If your sole reason for using routes is to make use of the named parameters, then I think it's better to fetch these parameters in your action methods because of two reasons:
Keeping the number of routes at a minimum will reduce the amount of time and resources spent by the router
Passing in the parameter keys in the url allows us to make use of more complex urls with optional parameters.
Any thoughts or advice on this topic are more than welcome!

Embedded mongoid referencing

My User model has_and_belongs_to_many :conversations.
The Conversation model embeds_many :messages.
The Message model needs to have a sender and a recipient.
I was not able to find referenced_in at the Mongoid documentation.
How do I assign the users in the message? I tried to follow something similar to this implementation, but kept getting BSON::InvalidDocument: Cannot serialize an object of class Mongoid::Relations::Referenced::In into BSON.
November 2013 Update: reference_in no longer works with Mongoid 3.0? Changed to belongs_to and it seems to work the same.
As it turns out, my structure of the Message referencing the User was appropriate, and the serialization error was related to associating the Users with the Conversation. Here is my structure and the creation steps. I appreciate any feedback on better practices, thanks.
class User
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
has_and_belongs_to_many :conversations
end
class Conversation
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
has_and_belongs_to_many :users
embeds_many :messages
end
class Message
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Paranoia
embedded_in :conversation
embeds_one :sender, class_name: 'User'
embeds_one :recipient, class_name: 'User'
field :content
field :read_at, type: DateTime
field :sender_deleted, type: Boolean, default: false
field :recipient_deleted, type: Boolean, default: false
belongs_to :sender, class_name: "User", inverse_of: :sender, foreign_key: 'sender_id'
belongs_to :recipient, class_name: "User", inverse_of: :recipient, foreign_key: 'recipient_id'
end
Where before I was trying to #conversation.build(user_ids: [#user_one,#user_two]), the appropriate way is to #conversation.users.concat([#user_one,#user_two]). Then you can simply #conversation.messages.build(sender: #user_one, recipient: #user_two).

How to link to an EmbeddedDocument in MongoMapper?

I'm not very confident about this schema design (suggestions welcome), but I have two collections:
Business
Customer
and each of them contains embedded documents:
Businesses contain Events
Customers contain Registrations
The class definitions are below, but first, the question. When I create a Business and add an Event, everything looks fine. When I create a Customer and add a Registration, everything looks fine. At this point, I can do:
ruby-1.9.2-p180 :380 > customer1.registrations.first.customer
=> #<Customer _id: BSON::ObjectId('4eb22a5bbae7a01331000019'), business_id: BSON::ObjectId('4eb215a9bae7a01331000001'), registrations: nil>
Perfect! But then... I add the Registration to the Event using event1.registrations << registration1, and now event1 has a different customer reference depending on whether I access it through the Event or through the Customer:
ruby-1.9.2-p180 :444 > customer1.registrations.first.customer
=> #<Customer _id: BSON::ObjectId('4eb22a5bbae7a01331000019'), business_id: BSON::ObjectId('4eb215a9bae7a01331000001'), posts: nil>
ruby-1.9.2-p180 :445 > business1.events.first.registrations.first.customer
=> #<Event _id: BSON::ObjectId('4eb21ab2bae7a0133100000f'), business_id: BSON::ObjectId('4eb215a9bae7a01331000001'), posts: nil>
ruby-1.9.2-p180 :446 > business1.events.first.registrations.first == customer1.registrations.first
=> true
Not perfect.... my best guess is that duplicates of registration1 have been embedded in both customer1 and event1? What I wanted was links between the Event and its many Registrations (which are owned and embedded in Customers). Is that possible with this schema?
This is what my models look like. They all have additional (and irrelevant) keys that are not displayed:
class Business
include MongoMapper::Document
many :events
many :customers
end
class Event
include MongoMapper::EmbeddedDocument
embedded_in :business
many :registrations
end
class Customer
include MongoMapper::Document
belongs_to :business
key :business_id, ObjectId
many :registrations
end
class Registration
include MongoMapper::EmbeddedDocument
embedded_in :customer
belongs_to :event
key :event_id, ObjectId
end
Yep. Registration is a MongoMapper::EmbeddedDocument so it's always embedded. That means because both Customer and Event have many :registrations, different registration objects will be embedded in each.
In MongoMapper, the embedded_in :customer just alias a customer method to return the document's parent. It's just a fancier way of calling _parent_document. That's why your event's registration's customer is an event object. (See source here).
The rule of thumb is to only embed when the child will always be used in context of its parent.

How-to: User has fans

I need users to be able to become fans of other users. How should I design/set this up?
I need to be able to view details of user fans.
For example. I have user: Foo. Foo has 3 fans. I'd like to be able to find the names of Foo's fans. As such:
foo = User.first
foo.name (returns 'Foo')
foo.fans.first.user.name (should return 'bar', since 'bar' is a fan of 'foo')
This is how I have it set up at the moment:
User model:
embeds_many :fans
references_many :fans
Fan model:
embedded_in :user, :inverse_of => :fans
referenced_in :user
In console, I do:
User.first.fans.create!(:user => User.first)
and I get:
Mongoid::Errors::InvalidCollection: Access to the collection for Fan is not allowed since it is an embedded document, please access a collection from the root document. I think the problem is, because the fan model is embedded in the user model which has a self-reference to the user model as well....
Your thoughts will be much appreciated.
How about a self-referential association:
class User
include Mongoid::Document
references_many :fans,
:class_name => 'User',
:stored_as => :array,
:inverse_of => :fan_of
references_many :fan_of,
:class_name => 'User',
:stored_as => :array,
:inverse_of => :fans
end
# let's say we have users: al, ed, sports_star, movie_star
sports_star.fans << al
movie_star.fans << al
sports_star.fans << ed
movie_star.fans << ed
movie_star.fans # => al, ed
al.fan_of # => sports_star, movie_star
The problem is that you are trying to do relational association using only embedded documents. When you have a Fan embedded inside a User, you can only access the Fan through its parent User. You can't do something like Fan.find(some_id) because there is no collection of Fan records.
Eventually, MongoDB will support virtual collections that will allow you to do this. For now, you have to use relational-type associations. If you want to use embedded documents in this case, you have to create some ugly and inefficient custom methods to search through parent records.
With MongoDB and Mongoid, I have found that you can switch between embedded and relational associations easily. SQL-type relationships and embedded relationships both have their place and can be used together to great effect.

drupal, rules, flag, date

I am using drupal 6. I have a node called [classroom]. I would like to have a [vacancy register] associated with each classroom.
vacancy register is a cck type with:
- uid
- nid
- join date
I would like for each user to [register] for a vacancy. I think I can use flag for this.
When a user joins, I can use rules to action an email to be sent to the user and the [classroom]->cck_email field.
I would like a rule schedule to also run every 30 days ( configurable ) to alert the user to confirm their [registration].
1a. If no registration is confirmed, then 14 days later, the user is [unregistered] from the classroom.
1b. If user confirms registration ( by clicking on a button or url ). then the rule 1 runs again.
I would like to confirms if my approach to this is correct.
Update:
I have been playing around with signup, but there are the rules schedule aspect of it that I find hard customising to my liking.
I'm trying to write a rules event for signup_signup and signup_cancel, then action it through rules schedule. But there a bit of existing signup code I have to look through.
Have to do too much custom work to signup, so I thought, its easier to just do it with rules and flags. The downside is having to also create the UI for it.
For the signup module,
I have the following rules event.
Could this be reviewed please?
<http://drupal.org/node/298549>
function signup_rules_event_info() {
return array(
'signup_signup' => array(
'label' => t('User signups to classroom'),
'module' => 'Signup',
'arguments' => array(
'userA' => array('type' => 'user', 'label' => t('UserA, which adds userB.')),
'userB' => array('type' => 'user', 'label' => t('UserB, which is added to UserA\'s list.')),
),
),
);
}
I don't know what to do with the arguments list.
I haven't looked at the signup module for some time, but I think that might be a better module for your case. The flag module is a good choice too, but the signup module is more geared towards what you are doing. Users signing up for content like a classroom.