Rails 3 parent and child association scopes optimization - ruby-on-rails-3

I have a parent has many children association in my project. I'm trying to get a list of children that have certain flags set from the parent when I render it.
For example this:
# some_controller
#thread = Thread.includes(:posts)
render :json => #thread.posts.as_json
will return something like
[
{
"id" => 1,
"posts" => [
{ "id" => 1, "flagged" => true },
{ "id" => 2, "flagged" => false }
]
}
]
I'm trying to get the output to be like this
[
{
"id" => 1,
"posts" => [
{ "id" => 2, "flagged" => false }
]
}
]
i.e.: only posts that are not flagged should be rendered.
I've overridden the as_json method in my model in order to do this as such:
def as_json(options = {})
...
{
:id => self.id,
:posts => self.posts
}
...
end
I realize that I can define a scope in the Posts model and use :posts => self.posts.not_flagged, but this causes an extra database query for every thread in my database (makes everything slow).
Aside from a default_scope on the Posts model how else could I solve this extra query problem?

I figured it out a bit after I posted.
I can add a scope in my Parent model to do this:
# Thread.rb
...
has_many :unflagged_posts, :class_name => "Post", :conditions => { :flagged => false }
...
And in my controller:
# some_controller
#threads = Thread.includes(:unflagged_posts)
This way ActiveRecord eager loads the posts with the flagged condition, rather than doing an extra query for each post!

Related

Netzke column locking

I saw a feature in Ext JS document - http://dev.sencha.com/deploy/ext-4.0.1/examples/grid/locking-grid.html. We can lock a column by set the option "locked" according the document, but when I did this in Netzke Grid, the grid disappears. Is there any specific method to achieve this. Below the sample code is given,
def configure(c)
super
c.model = "Product"
c.title = "Product List"
c.columns = [
{
:name => :name,
:text => "Name",
:read_only => true,
:locked => true
},
{
:name => :price,
:text => "Price"
},
{
:name => :date,
:text => "Date"
}
]
end

Laravel adding/finding relationships for relationships

How to find relationships for relationships with Eloquent ORM? Currently I have something like this. Simple relationship. I can find Image and it's photographer. Now I need to do something more complex, I need to find also photographers tags.
dump looks like this
object(Image) {
["attributes"] => [],
["relationships"] =>
["photographer"] =>
["attributes"] => [],
["relationships"] =>
}
But I need to add tags relationship so It would look like this
object(Image) {
["attributes"] => [],
["relationships"] =>
["photographer"] =>
["attributes"] => [],
["relationships"] =>
["tags"] =>
["attributes"] => [],
["relationships"] =>
}
How is that possible?
/Image model
public function photographer()
{
return $this->belongs_to('Photographer');
}
public function tags()
{
return $this->has_many_and_belongs_to('Tag', 'tag_relationships');
}
/Controller
$images = Image::with(['photographer'])->order_by('updated_at', 'desc')->get();
you just use laravel's dot syntax:
Image::with(['photographer', 'photographer.tags', 'photographer.tags.categories]) ....

Mapping IDictionary<Entity, Component> with MappingByCode

How can I map IDictionary<Entity, Component>? I've done this way:
Map<GeneralResourceType, Quantity>(x => x.BookedResources,
c =>
{
c.Key(ck => ck.Column("ProposedAction"));
c.Table("BookedResources");
},
k => k.ManyToMany(key => key.Column("ResourceTypeId")),
r => r.Component(qc => QuantityMapping.Mapping()));
(where GeneralResourceType is a mapped Entity and Quantity is a ValueObject). But during the call of BuildSession() exception is thrown:
NHibernate.MappingException : An association from the table BookedResources refers to an unmapped class: {MyNamespace}.Quantity.
Seams like it tries to find ClassMapping for Quantity, while value part mapped as Component.
First variant:
Map component in separate class inherited from ComponentMapping generic class.
Map dictionary property as follows:
Map(x => x.BookedResources, c =>
{
//any options access, cascade etc
});
Second variant (inline):
Map(x => x.BookedResources, x =>
{
//any options access, cascade etc
},
x => x.Element(),
x => x.Component(c =>
{
c.Class<Quantity>();
c.Property(p => p.Amount);
c.Property(p => p.Unit);
// any other properties
}
));

CouchDB: How to get all documents?

I am using CouchRest for Rails and I'm having problems understanding the documentation (or lack of it).
response = #db.save_doc( { :key => 'value', 'another key' => 'another value' } )
#doc = #db.get(response['id'])
doc = #db.get(:key => 'value')
After saving the doc, how do I get all the documents where the key => 'value' =
thanks
You need to create a view where 'key' is your index. Then you can query that view.
Based loosely on the docs:
#db.save_doc({
"_id" => "_design/my_view",
:views => {
:test => {
:map => "function(doc){ emit(doc.key,null)}"
}
}
})
puts #db.view('my_view/test', 'key' => 'value')['rows'].inspect

Can Mongoid `any_of` include use of external document relationships?

I'm using MongoDB with Mongoid and trying to put in place a rudimentary search as a placeholder before we look at weighting, etc. The any_of method seems to be finding my embedded documents but not those linked by relations. Does anyone know if any_of can include relationships to other documents in the db, and if so what the syntax would be?
belongs_to :principal #owner
belongs_to :account #owner
scope :search, ->(text) { any_of(
{:description => /#{text}/i},
{:name => /#{text}/i},
{"entries.title" => /#{text}/i},
{"entries.description" => /#{text}/i},
{:tags => /#{text}/i},
{"account.name" => /#{text}/i}, # Not finding by account name - because account isn't embedded?
{"principal.name" => /#{text}/i} # Not finding by principal name - because not embedded?
)}
No, any_of is the equivalent of a MongoDB $or query, so the native MongoDB would be something like:
db.collection.find(
{ "text" :
{ "$or" :
[ { "account.name" => /#{text}/i }, { "principal.name" => /#{text}/i } ]
}
})
Mongo queries only run over a single collection, so to resolve the account.name and principal.name fields they'd need to be embedded inside the document, e.g.
{
text:
{
description: "...",
name: "...",
account: { name: "..." },
principal: { name: "..." }
}
}