class Person
include Mongoid::Document
field :name
embeds_many :addresses
end
class Company
include Mongoid::Document
field :name
embeds_many :addresses
end
class Address
include Mongoid::Document
embedded_in :addressable, inverse_of :addresses
end
I tried something like this
company = Company.first
person = Person.first
address = Address.new
company.addresses << address
company.save
=>true
person.addresses << address
person.save
=>true
But I didn't found address embedded in person.But I found that it was
embedded in company.
Did anyone know why? Or Can't I embed address in multiple document.
Again while I reversed like this
person.addresses << address
person.save
=>true
company.addresses << address
company.save
=>true
I found address was embedded in person not in company..
Any Ideas.
If clone() doesn't work you could create a new Address record based on the attributes of the old Address. This will be a new object and should successfully save.
Try to clone your address :
person.addresses << address
person.save
=>true
company.addresses << address.clone
company.save
=>true
All document even embedded are _id so it not new_record in second case if you ton clone it.
This might help you,
company.addresses.new.attributes = address.attributes
company.save
Related
My main models look like this,
class BusStation(models.Model):
name = models.CharField()
location = models.CharField()
class Bus(models.Model):
name = models.CharField()
routes = models.ManyToManyField(BusStation)
If a user intends to board a bus, they would need to include take_off_station and destination_station within their search query. The problem is, I'm trying to get the list of buses that contain both take_off and destination points within their route.
I tried:
Bus.objects.filter(
Q(routes__name__icontains=take_off_station) &
Q(routes__name__icontains=destination_station))
this doesn't return anything. When I replaced & for | it returns a queryset that contains at least one of the results i needed. So Please, How do I return all buses that contain both, take_off and Destination within their routes
I want to pass an array from a Ruby file to another one.
I have a three files:
main.rb
company.rb
applicant.rb
Here is the code for main.rb:
require './src/company.rb'
require './src/applicant.rb'
company = Company.new('data/boundless.json')
company.find_applicants('google')
Here is the code for company.rb:
require 'json'
require_relative 'applicant.rb'
class Company
attr_accessor :jobs , :arrOfApp
def self.load_json(filepath)
file = File.read(filepath)
return JSON.parse(file)
end
def initialize(filePath)
# Load the json file and loop over the jobs to create an array of instance of `Job`
# Assign the `jobs` instance variable.
jobs=Array.new
data_hash = Company.load_json(filePath)
numberOfJobs= data_hash['jobs'].length
for i in 0 ... numberOfJobs
jobs[i]=data_hash['jobs'][i]['applicants']
# puts jobs
end
end
## TODO: Impelement this method to return applicants from all jobs with a
## tag matching this keyword
def find_applicants(keyWord)
app =Applicant.new
arrOfApp=Array.new
app.data_of_applicant(jobs)
end
end
And finally the code for applicant.rb:
require_relative 'company.rb'
class Applicant
attr_accessor :id, :name, :tags
def initialize
end
def data_of_applicant(j)
id=Array.new
name=Array.new
tags=Array.new
puts j
end
end
The program reads a JSON file to get some information from it. Whenever I try to print the value being sent to the applicant file nothing is printed.
You can't pass an array from a ruby file to another one., you only can pass data between classes and objects.
Other possibilities which may help:
constants (Defined with starting capital letter)
global variables (starting with $)
Singletons
To keep data inside the class instances (objects) you need attributes (variables starting with #).
You can find this concepts in every beginner manual of ruby (and if not, then the manual is not worth to be used)
You made another common error.
Let's check it with a small example:
class Company
attr_accessor :jobs
def initialize()
jobs='This should be assigned to my accessor jobs'
end
end
puts Company.new.jobs
The result is an empty line.
What happend? In the initialize-method you define a local variable jobs. Local means, it is only available in the method ans is lost when the method leaves.
Correct would be 1) using the instance variable:
class Company
attr_accessor :jobs
def initialize()
#jobs='This should be assigned to my accessor jobs'
end
end
or 2) using the accessor method:
class Company
attr_accessor :jobs
def initialize()
self.jobs='This should be assigned to my accessor jobs'
end
end
In both cases the puts Company.new.jobs returns the text you defined.
See also Ruby instance variable access
if i'm reading this correctly, you're asking ruby to make the calculation, but never stating that it should be printed. i believe changing the last line of your main.rb to this:
puts company.find_applicants('google')
should suffice.
It might be the most dumb question and my apologies for the same but I am confused
I have the following entity:
class Profile(ndb.Model):
name = ndb.StringProperty()
identifier = ndb.StringProperty()
pic = ndb.BlobKeyProperty() # stores the key to the profile picture blob
I want to delete the "pic" property value of the above entity so that it should look as fresh as if "pic" was never assigned any value. I do not intend to delete the complete entity. Is the below approach correct:
qry = Profile.query(Profile.identifier==identifier)
result_record_list = qry.fetch()
if result_record_list:
result_record_list[0].pic.delete() # or result_record_list[0].pic = none # or undefined or null
I am deleting the actual blob referred by this blob key separately
assign None to it and put it back to the datastore.
result_record_list[0].pic = None
result_record_list[0].put()
The datastore is an OO schemaless databse. So you can add and remove properties from the the Kind (ndb.Model) without the need of a schema update.
If you also want to cleanup the entities look at this anwser from Guido
Given a simple embedded relationship with an extension like this:
class D
include Mongoid::Document
embeds_many :es do
def m
#...
end
end
end
class E
include Mongoid::Document
embedded_in :d
end
You can say things like this:
d = D.find(id)
d.es.m
Inside the extension's m method, how do access the specific d that we're working with?
I'm answering this myself for future reference. If anyone has an official and documented way of doing this, please let me know.
After an hour or so of Googling and reading (and re-reading) the Mongoid documentation, I turned to the Mongoid source code. A bit of searching and guesswork lead me to #base and its accessor method base:
embeds_many :es do
def m
base
end
end
and then you can say this:
d = D.find(id)
d.es.m.id == id # true
base is documented but the documentation is only there because it is defined using attr_reader :base and documentation generated from attr_reader calls isn't terribly useful. base also works with has_many associations.
How did I figure this out? The documentation on extensions mentions #target in an example:
embeds_many :addresses do
#...
def chinese
#target.select { |address| address.country == "China"}
end
end
#target isn't what we're looking for, #target is the array of embedded documents itself but we want what that array is inside of. A bit of grepping about for #target led me to #base (and the corresponding attr_reader :base calls) and a quick experiment verified that base is what I was looking for.
I'm unable to workout how you can get objects from the Google App Engine Datastore using get_by_id. Here is the model
from google.appengine.ext import db
class Address(db.Model):
description = db.StringProperty(multiline=True)
latitude = db.FloatProperty()
longitdue = db.FloatProperty()
date = db.DateTimeProperty(auto_now_add=True)
I can create them, put them, and retrieve them with gql.
address = Address()
address.description = self.request.get('name')
address.latitude = float(self.request.get('latitude'))
address.longitude = float(self.request.get('longitude'))
address.put()
A saved address has values for
>> address.key()
aglndWVzdGJvb2tyDQsSB0FkZHJlc3MYDQw
>> address.key().id()
14
I can find them using the key
from google.appengine.ext import db
address = db.get('aglndWVzdGJvb2tyDQsSB0FkZHJlc3MYDQw')
But can't find them by id
>> from google.appengine.ext import db
>> address = db.Model.get_by_id(14)
The address is None, when I try
>> Address.get_by_id(14)
AttributeError: type object 'Address' has no attribute 'get_by_id'
How can I find by id?
EDIT: It turns out I'm an idiot and was trying find an Address Model in a function called Address. Thanks for your answers, I've marked Brandon as the correct answer as he got in first and demonstrated it should all work.
I just tried it on shell.appspot.com and it seems to work fine:
Google Apphosting/1.0
Python 2.5.2 (r252:60911, Feb 25 2009, 11:04:42)
[GCC 4.1.0]
>>> class Address(db.Model):
description = db.StringProperty(multiline=True)
latitude = db.FloatProperty()
longitdue = db.FloatProperty()
date = db.DateTimeProperty(auto_now_add=True)
>>> addy = Address()
>>> addyput = addy.put()
>>> addyput.id()
136522L
>>> Address.get_by_id(136522)
<__main__.Address object at 0xa6b33ae3bf436250>
An app's key is a list of (kind, id_or_name) tuples - for root entities, always only one element long. Thus, an ID alone doesn't identify an entity - the type of entity is also required. When you call db.Model.get_by_id(x), you're asking for the entity with key (Model, x). What you want is to call Address.get_by_id(x), which fetches the entity with key (Address, x).
You should use long type in get_by_id("here").
Int type must have a error message.