I have a collection in a mongodb imported from csv file, and I want to load that into my ruby-on-rails3.2.13 app to list the collections document in homepage.
I have used mongoid as an object document mapper.
Can anyone please tell me the process for this problem?
it should be plain and simple if I understood your question.
say you have a model that uses mongoid
class Model
include Mongoid::Document
#define fields here
end
then in controller
#records = Model.all
then you should get an array of records
Related
I'm using Mongoid to build a Rails 4 app.
The problem I'm having right now is how to filter some Mongoid objects through their own relations and have a Mongoid::Criteria at the end instead of an Array.
This is some example code:
class Editor
include Mongoid::Document
has_many :books
def likes
books.collect { |book| book.likes }
end
end
class Book
include Mongoid::Document
belongs_to :editor
end
What I would like to be able to do is something like:
Editor.last.likes.where(:created_at.gt => 10.days.ago)
but of course this doesn't work as Editor.last.likes returns an Array, not a Mongoid::Criteria
I know Mongoid has an aggregation framework but it's not entirely clear to me how to use it, nor if it's the best way to solve my problem.
Suggestions?
TIA,
ngw
The biggest problem you have here is that MongoDB does not do joins like a relational database does. All of the work you are getting for convenience when traversing object properties is being done client side while pulling in the 'related' documents over the wire in a query. But in sending a query, the two collections cannot be joined.
Your workaround solution is to work with the data you can get at in separate queries in order to target the results. One approach is here: rails mongoid criteria find by association
There should be other examples on Stack Overflow. You're not the first to ask.
Is there any gem/plugin for ruby on rails which gives the ability to define custom fields in a model at runtime with no need to change the model itself for every different field.
I'm looking for something like Redmine acts_as_customizable plugin which is packaged as a gem usable in the rails way, i.e.
gem 'gemname'
rails g something
rails db:migrate
class Model < ActiveRecord::Base
acts_as_something
end
Here are the CustomField and the CustomValue classes used in Redmine.
Edit:
Since my question is not clear I add a brief use case which explains my need better:
I want users to be able to design their own forms, and collect data
submitted on those forms. An important decision is the design of how
these custom dynamic records are stored and accessed.
Taken from here, in this article approach the problem with different ideas, but they all have drawbacks. For this reason I'm asking if the issue has been approached in some gem with no need to rethink the whole problem.
I'm not aware of a gem that does this, but serialize works quite well and it's a built-in. You get a NoSQL-ish document store backed by JSON/YAML.
If you allow user to create a custom form, you can pass nested arrays et cetera directly into the attribute. However, if you need to validate the structure, you're on your own.
I'm afraid it could be tricky and complicated to do it in ActiveRecoand (generally in standard relational database). Take a look at http://mongoid.org/docs/documents/dynamic.html - this mechanism is using nosql feature.
You can also may try the following trick:
1/ Serialize a hash with your custom fields in the database column, for example { :foo => 'bar', :fiz => 'biz' }
2/ After load a record from database do some metaprogramming and define corresponding methods on the record's singleton class, for instance (assume that custom fields are stored and serialized in custom_fields column):
after_initialize :define_custom_methods
# ..or other the most convinient callback
def define_custom_methods
# this trick will open record's singleton class
singleton_class = (class << self; self; end)
# iterate through custom values and define dynamic methods
custom_fields.each_with_key do |key, value|
singleton_class.send(:define_method, key) do
value
end
end
end
Since rails 3.2 you can use store method. Just include following in your model:
store :properties, accessors: [:property1, :property2, :property3...]
You only need to change your model once (to add properties field to db table). You can add more properties later without altering the schema.
The way this works is by serializing properties hash into YAML and saving it into database. It it suitable for most cases, but not if you'd like to use these values in db queries later.
I don't know a gem, but this can be accomplished be creating a table called custom_fields with a name column and possibly a datatype column if you wanted to restrict fields by datatype.
Then you create a join table for a custom field to your desired table and a value and do whatever validations you want.
I want to query many different collections from a model in rails.
For example:
class Statistics
include Mongoid::Document
end
I want to be able to query a statistics or maybe a my_stats collection. Is that possible? How can I do it?
Your question isn't clear. If you want to know how to define your own collection name, instead of having Mongoid auto-generate one via the class name/ActiveSupport, you can do that using the store_in method. Like so:
class Statistics
include Mongoid::Document
store_in :mystats
end
If you're asking how to search multiple collections with one query, that isn't possible in MongoDB, as far as I'm aware.
I'm trying to turn a database record into an exportable document, such that I can reimport it and update the database. I'd just use CSV but it's also nested, say Country has_many Provinces has_many Cities.
I've tried dumping YAML per this earlier question:
File.open("#{RAILS_ROOT}/lib/tasks/canada.yml", 'w') do |file|
country = Country.find(1)
country.provinces
country.cities
YAML::dump(country, file)
end
But when I load, it doesn't:
country = YAML.load_file("#{RAILS_ROOT}/lib/tasks/canada.yml")
I even tried hacking the new_record flag per this article but it doesn't change anything. I'm using Rails 3.x.
This must be something other people have done before. How? Or do I need to approach the problem differently?
I guess the problem is that country.save will not produce a new record in the database? You can try Country.create!(country.serializable_hash). That will at least create a new record based on the attributes of country. The country id will be changed and I guess nested objects (Province, City) will not be handled properly.
I am trying to create an ActiveRecord model called 'Search' without a table. I keep getting this error when I do #search = Search.new.
sql::Error: Table 'searchdemo_development.tablelesses' doesn't exist: SELECT * FROM tablelesses
I am using the idea from this comment: Rails model without database. I also get the same kind of error doing the basic:
class Search < ActiveRecord::Base
end
How do I get ActiveRecord stop looking for a table?
I can think of a few reasons you might want to do something like this. Perhaps you want to leverage some of the non-db-related methods on ActiveRecord or you want to pass your object to something that expects and ActiveRecord instance. Without more info, it is impossible to say whether the choice to use AR here is correct or incorrect.
In any event, if you want to continue on this path...
check out this Railscast
http://railscasts.com/episodes/121-non-active-record-model
and also checkout this gem:
http://github.com/kennethkalmer/activerecord-tableless-models/tree/master
Why in the name of the lord would you want an actve record model without a table? The purpose of an active record model is to communicate with a database. I assume that it is impossible to have an active record model without a db table.
Perhaps you want a regular class?
class Search
# your methods here
end