How to validate that an array is not empty in Mongoid? - ruby-on-rails

class Foo
include Mongoid::Document
field :bars, type:Array
end
How to validate that the bars array is not empty?

Try the standard presence validator:
class Foo
include Mongoid::Document
field :bars, type: Array
  validates :bars, presence: true
end
This works because the presence validator uses the blank? method to check the attribute during validation.

Related

Migrating from active record/postgres to mongodb/mongoid and I cannot create/save

I have the following models in mongoid(i.e., was previously in active record).Trying save product item group along with item selection option but I am running into no method "all_of" error.And I am new to using mongoid/mongobd with ROR.
class ProductItemGroup
include Mongoid::Document
include Mongoid::Timestamps
store_in database: "cnc_product_ms"
field :name, localize: true
field :description, localize: true
field :product_item_selection_type, type: String
embeds_one :item_selection_option
has_and_belongs_to_many :service_categories
field :service_category_ids, type: Array
end
class ItemSelectionOption
include Mongoid::Document
include Mongoid::Timestamps
include SimpleEnum::Mongoid
store_in database: "cnc_product_ms"
as_enum :selection_type,multiple: 1, single: 2
as_enum :mandatory_selection_type, atleast_one: 1, many: 2
field :selection_type, type: Integer
field :selection_mandatory, type: Boolean, default: false
field :mandatory_selection_type, type: Integer
embedded_in :product_item_group
end
controller /form
class ProductItemGroupForm < ApplicationForm
attr_accessor(:product_item_group)
def create
#product_item_group = ProductItemGroup.new(params)
#product_item_group.save!
end
end
on save!, I am running into following error
NoMethodError: undefined method `all_of' for #<Class:0x00007fd96afea600>
from /Users/90srebel/.rvm/gems/ruby-2.6.4/gems/activerecord-6.0.3.1/lib/active_record/dynamic_matchers.rb:22:in `method_missing'
Got the issue. I am closing this question.
What I did wrong was,
I declared has_and_belongs_to_many in product_item_group model but forgot to declare the same thing in service_category model. Silly

Mongoid: Parent of embedded document returning nil from field default lambda

I have two Mongoid models defined as
class Owner
include Mongoid::Document
include Mongoid::Timestamps
embeds_many :pets, class_name: 'Pet', inverse_of: :owner
field :special_unit, type: String
end
class Pet
include Mongoid::Document
include Mongoid::Timestamps
embedded_in :owner, inverse_of: :pets
field :special_unit, default: lambda {
if owner
owner.special_unit
else
'default_value'
end
}
end
If I create a persisted Owner with special_unit field set.
owner = Owner.create(special_unit: 'foo')
owner.pets.create
owner.pets.first.special_unit
=> 'default_value'
The owners pet has default_value as the value special unit. This is because pet is returning nil inside the lambda that the field default is calling. If I call _parent inside the lambda nil is also returned. Does anyone know why this is?
For further context I am able to call #owner and #_parent on an instance of Pet and return the expected owner. It's during the field default assignment that nil is returned.
I am using mongoid 6.4

Mongoid Polymorphic Association Rails

Work env: Rails 4.2 mongoid 5.1
Below are my models:
class Tag
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
belongs_to :entity_tags, :polymorphic => true
end
class EntityTag
include Mongoid::Document
include Mongoid::Timestamps
field :tag_id, type: String
field :entity_id, type: String // Entity could be Look or Article
field :entity_type, type: String // Entity could be Look or Article
field :score, type: Float
end
class Look
include Mongoid::Document
include Mongoid::Timestamps
has_many :tags, :as => :entity_tags
end
class Article
include Mongoid::Document
include Mongoid::Timestamps
has_many :tags, :as => :entity_tags
end
We are trying to implement polymorphic functionality between Looks and Articles to Tags.
i.e. Let's say we have a Tag named "politics", and we would like to add the tag to an Article with the score '0.9' and to a Look with the score '0.6'. The Score should be saved at the EntityTags Model.
The problem:
The first assign of the tag works, but then when I try to assign the same tag to another entity, it removes it and reassigns it from the first one to the latter.
The assignment looks like the following:
entity.tags << tag
Does anybody know the proper way to save associations and create the EntityTag Object with the correct polymorphism and assignment properly?
Thanks!
I've managed to implement a non-elegant working solution based on the following answer in this link

Rails 3: Mongoid validation issue

Using Mongoid, I am trying to validate the :code input on the submission form to make sure they are using a proper code that is already stored in the database. There are about 2000+ codes so a helper method array collection wouldn't be feasable.
What is the best way to do this?
I was thinking of doing an inclusion validation, like this:
class Request
include Mongoid::Document
field :code, type: String
validates :code, :presence => true,
:inclusion => { :in => proc { Listing.all_codes } }
end
Then the model that has all the stored codes, like this:
class Listing
include Mongoid::Document
field :code, type: String
def self.all_codes
where(:code => exists?) # <--- this is broken
end
end
But I can't seem to get this to function the way I would like. Any feedback would be much appreciated.
Your Request model looks fine. But the Listing.all_codes needs to return an array of only codes. so:
class Listing
include Mongoid::Document
field :code, type: String
def self.all_codes
only(:code).map(&:code)
end
end

Why doesn't mongoid add my nested attributes on new()?

I can't seem to figure out why Mongoid won't set the nested attributes for a child object when I create a new parent. I want to create a new Folio, add one child Feature, then push it on the Folios array on Profile.
I have a Profile, which embed many Folios, which embed many Features:
class Profile
include Mongoid::Document
include Mongoid::Timestamps::Updated
#regular fields here; removed for brevity
embeds_many :folios, class_name: "Folio"
end
class Folio
include Mongoid::Document
include Mongoid::Timestamps::Updated
accepts_nested_attributes_for :features
embedded_in :profile
field :name
field :desc
field :order, type: Integer, default:0
embeds_many :features
attr_accessible :name, :desc, :order
end
class Feature
include Mongoid::Document
include Mongoid::Timestamps::Updated
embedded_in :folio
belongs_to :project
field :content_type, type: Integer #ContentType
field :content_id
field :txt, type: String
field :order, type: Integer, default:0
attr_accessible :project_id, :content_type, :content_id, :txt, :order
end
Controller:
def new
#folio = Folio.new
#folio.features.build
end
def create
#folio = Folio.new(params[:folio])
##folio.features is still empty here.
#profile.folios << #folio
#profile.save
render "create_or_update.js"
end
In create, the param hash looks good:
{"folio"=>{"id"=>"new", "name"=>"new name", "desc"=>"new description", "features_attributes"=>{"0"=>{"project_id"=>"4ea0b68e291ebb44a100000a", "content_type"=>"1", "content_id"=>"4ea0b68e291ebb44a100000d", "txt"=>"note here"}}}, "commit"=>"Save", "action"=>"create", "controller"=>"folios"}
But #folio.features is still empty.
This worked fine with AR, if I remember. Strangely, there is no features_attributes=() method on Folio. I thought that was required for the nested attributes to work? What am I missing?
This is on Rails 3.1 with Mongoid 2.2.3.
have you tried enabling AutoSave true for features in Folio document
class Folio
include Mongoid::Document
include Mongoid::Timestamps::Updated
accepts_nested_attributes_for :features , :autosave => true
embedded_in :profile
end

Resources