Updating record with Mongoid in Rails - ruby-on-rails

I am testing this from rails console:
Credential.last.token => nil
Credential.last.update_attribute :token, '123' => true
Credential.last.token => nil
Here is my class:
class Credential
include Mongoid::Document
include Mongoid::Timestamps
field :_id, type: String
field :user_id, type: Integer
field :code, type: String
field :provider, type: String
field :token, type: String
end
What am I doing wrong?

If you have identity map enabled you'll need to wrap that in
Mongoid.unit_of_work { Credential.last.token }
Mongoid caches the queries. It is not a problem for web requests, but in the console you won't see the change unless you do it in the unit of work block, or restart the console (not just a reload)

I had to put
attr_accessor :token, ...

Related

Rails Neo4j Migration Argument Error

So I have these two classes
class Tweet
include Neo4j::ActiveNode
property :content, type: String
property :created_at, type: DateTime
property :updated_at, type: DateTime
has_one(:user, :tweeted).from(:User)
end
class User
include Neo4j::ActiveNode
property :username, type: String
property :name, type: String
property :email, type: String, default: ''
validates :email, :username, uniqueness: true
property :encrypted_password
has_many(:Tweet, :tweeted)
end
And everytime I run rails neo4j:migrate it gives error like this
ArgumentError: The 'type' option must be specified( even if it is nil) or origin/rel_class must be specified (Class#tweeted)
How to properly create relationship between nodes in neo4jrb?
As the error message describes, you didn't explicitly define the type of your tweeted relation. Take a look at the official documentation for further details. However, the following should work:
class Tweet
include Neo4j::ActiveNode
property :content, type: String
property :created_at, type: DateTime
property :updated_at, type: DateTime
has_one :out, :author, type: :author, model_class: :User
end
class User
include Neo4j::ActiveNode
property :username, type: String
property :name, type: String
property :email, type: String, default: ''
validates :email, :username, uniqueness: true
property :encrypted_password
has_many :in, :tweets, origin: :author
end

Why my app is taking this class as uninitialized constant Booking::String?

I am using mongodb through mongoid gem in rails. I am new to it. I've created a model in this which is following:
class Booking
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
embeds_many :extras
accepts_nested_attributes_for :extras
field :bedroom, type: Integer
field :bathroom, type: String
field :frequency, type: String
field :extras, type: String
field :zipcode, type: Integer
field :date, type: String
field :time, type: String
field :date_timestamp, type: Time
field :first_name, type: String
field :last_name, type: String
field :email, type: String
field :address, type: String
field :apartment, type: Strng
field :phone, type: String
field :alt_phone, type: String
field :key_info, type: Integer
field :key_details, type: String
field :coupon_code, type: String
field :gift_card_code, type: String
field :gift_card_amount, type: Float
field :referral_amount, type: Float
field :final_amount, type: Float
field :created_at, type: Time
field :updated_at, type: Time
end
And whenever I access it index page having code
class BookingsController < ApplicationController
def index
#bookings = Booking.all
end
end
It returns me uninitialized constant Booking::Strng error. I've spend hour in finding out its reason. Can anyone help me to resolve this.
Because String is spelled with an i :) See your :apartment line.
Btw, I'll add that this is so common in programming, never trust your eyes, all I did here was copied the string from the error and Cmd+F searched for it in this page (your code).

Ruby addtoset to a array field

When adding a value into a array field of a class, I am getting the error given below:
" Cannot apply $addToSet to a non-array field. Field named 'chat_user_ids' has a non-array type NULL in the document _id: ObjectId('5705fd637261695baa0f0000') ".
class Wall
include Mongoid::Document
include Mongoid::Timestamps::Created
include Mongoid::Timestamps::Updated
include Geo
include WallSearch
include Common
field :message, type: String
field :user_id, type: BSON::ObjectId
field :city, type: String
field :tag_id, type: BSON::ObjectId
field :group_id, type: BSON::ObjectId
field :tag_name, type: String
field :status, type: Boolean, default: true
field :abuse_count, type: Integer, default: 0
field :latitude, type: String
field :longitude, type: String
field :state, type: String
field :address, type: String
field :location, type: Array
field :chat_user_ids, type: Array
chat_user_ids is the array to which I am adding a value.
wall = Wall.where(_id: wall_id).first
return false unless wall.present?
wall.add_to_set(chat_user_ids: user_id)
user_id should rather be [user_id]
wall.add_to_set(chat_user_ids: [user_id])

Query embedded document using slug array in Mongoid

I have 3 models, that all have use the gem - https://github.com/digitalplaywright/mongoid-slug - that creates a _slugs field from the models title field.
I have the slug for one of my articles and I need to find the issue it belongs to. I have tried a whole deal of things, but nothing seems to work.
Any advice on what the correct query is to get the issue that belongs to the article with my article slug?
Query that doesn't work:
p = Publication.find("my-publication")
p.issues.where(:'articles._slugs'.in => ["an-article-slug"]).first
Publication model:
class Publication
# 1. Include mongoid stuff
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Slug
# 2. Define fields
field :title, type: String
field :description, type: String
field :published, type: Boolean, default: false
field :live, type: Boolean, default: false
field :show_walkthrough, type: Boolean, default: true
field :subscription_duration, type: String, default: "Subscription Duration"
field :subscription_price, type: String, default: "Price"
field :sell_issues_separately, type: String, default: "Individual Issue Sale"
field :issue_price, type: String, default: "Price"
field :previewed_on_device, type: Boolean, default: false
field :shareable, type: String, default: "Make Articles Shareable Online"
field :urban_airship_key, type: String
field :urban_airship_secret, type: String
field :urban_airship_master_secret, type: String
# 3. Set attributes accesible
attr_accessible :title, :description, :live, :published, :show_walkthrough, :subscription_duration, :subscription_price, :sell_issues_separately, :issue_price, :cover_image_attributes, :logo_image_attributes, :shareable, :urban_airship_key, :urban_airship_secret, :urban_airship_master_secret
# 4. Set slug
slug :title, reserve: ['new', 'edit', 'walkthrough', 'email', 'previewer', 'privacy', 'support', 'manifest', 'feed', 'demo', 'existence', 'switch']
# 5. Set associations
belongs_to :user
embeds_many :issues, order: :created_at.desc, cascade_callbacks: true
end
Issue model:
class Issue
# 1. Include mongoid stuff
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Slug
# 2. Define fields
field :title, type: String
field :description, type: String
field :published, type: Boolean, default: false
field :last_push_at, type: DateTime, default: Time.now
field :published_at, type: DateTime, default: Time.now
field :no, type: Integer, default: 0
field :color, type: String
field :free, type: Boolean, default: false
# 3. Set attributes accesible
attr_accessible :title, :description, :published, :last_push_at, :published_at, :no, :color, :free, :cover_image_attributes
# 4. Set slug
slug :title, scope: :publication, reserve: ['new', 'edit', 'publish', 'update_order']
# 5. Set associations
embedded_in :publication
embeds_many :articles, :as => :articleable, :class_name => 'Article', cascade_callbacks: true, order: :no.desc
embeds_one :cover_image, :as => :imageable, :class_name => 'Image', cascade_callbacks: true, autobuild: true
end
Article model:
class Article
# 1. Include mongoid stuff
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Slug
# 2. Define fields
field :title, type: String
field :author, type: String
field :lead, type: String
field :body, type: String
field :no, type: Integer
# 3. Set attributes accesible
attr_accessible :title, :author, :lead, :body, :no, :article_image_attributes, :article_images_attributes, :article_images_attributes
# 4. Set slug
slug :title, scope: :articleable
# 5. Set associations
embedded_in :articleable, polymorphic: true
embeds_one :article_image, :as => :imageable, :class_name => 'Image', cascade_callbacks: true, autobuild: true
embeds_many :article_images, :as => :imageable, :class_name => 'Image', cascade_callbacks: true
end
UPDATED With new queries and results
I can get the publication using the query suggestion of #mu below:
I can't get the issue using the same query though:
And here you can see the _slugs field if I take the first article in the first issue of the publication:
What am I doing wrong here? The query seems to work nicely when grabbing a publication. Why doesn't it work nicely when grabbing an issue?

Mongoid create new Users

I'm trying to write an example app using Ruby on Rails and the Mongoid Mapper.
For some kind of Testing I want to write 1000 Testusers into MongoDB...
With the code bolow Mongoid is not able to write unique uid's. In my ruby console i got the right number for the counter but not for the uid.
Does anybody know what I forgot?
class User
include Mongoid::Document
include Mongoid::Timestamps
def self.create_users
(1..1000).each do |f|
user = User.new(uid: f.to_s, first_name: "first_name", last_name: "last_name", e_mail: "e_mail")
user.save!
puts f
puts user.uid
end
end
field :uid, :type => String
field :first_name, :type => String
field :last_name, :type => String
field :e_mail, :type => String
field :messages, :type => String
attr_accessible :first_name, :last_name, :e_mail
validates_presence_of :uid, :first_name, :last_name, :e_mail
validates_uniqueness_of :uid
has_many :messages
end
You don't have to provide the field uid in your models. MongoId add the id field for you and manages the value during the create operation.
Simply remove field :uid, :type => String from model
If you want to use your own ids you can change the name of the uid field to _id and it should work just fine. However, the default generated mongo _id will make it easier to scale and using it removes one of the more difficult aspects of sharding if you ever need that feature.
If you want to use the ones that are generated by default, they are included automatically unless overridden explicitly (behavior which you have seen) so just remove your custom field and you should be all set.
You can read more about ObjectIds here.

Resources