I have a generator class that I can run like this:
rails g shopping_template --attributes=email:hello
It recognizes email as input. But when I want to add several attributes its not working, it only recognizes email:
rails g shopping_template --attributes=email:hello,name:hans,house:big
Ho do I have to change --attributes=email:hello,name:hans,house:big so that its recognized correctly as a hash?
Here's the code from the class:
class_option :attributes,
type: :hash,
default: {}
Check the Thor document. This is the correct way to pass a hash:
--option=name:string age:integer
So for your example, it would be:
--attributes=email:hello name:hans house:big
Related
I'm using a jsonb field in my Rails application and have installed the gem attr_json. Is there a way to receive the defined json_attributes programmatically? With a "normal" rails attribute, I would just do #instance.attribute_names. But with attr_json is there any way how to have the json_attributes returned?
class Vehicle < Item
include AttrJson::Record
attr_json :licence_plate, :string, container_attribute: "custom_attributes_indexed"
attr_json :brand, :string, container_attribute: "custom_attributes_indexed"
attr_json :serial_number, :string, container_attribute: "custom_attributes_indexed"
attr_json :inventory_number, :string, container_attribute: "custom_attributes_indexed"
end
For this code I would like to do something like #vehicle.json_attribute_names and have the following returned
["licence_plate", "brand", "serial_number", "inventory_number"]
You can retrieve the defined json_attributes via: Vehicle.attr_json_registry.attribute_names
But even simpler to retrieve the attributes via the rails method attribute names is to add rails_attribute: true to your attr_json definitions. This will return all the "normal" attributes and the JSON attributes as an array.
[...]
attr_json :licence_plate, :string, container_attribute: "custom_attributes_indexed", rails_attribute: true
[...]
I have a Rails app that uses a JSONB column in Postgres and without any other gems I can call the following to get the keys...
Given a model Inspections with a JSONB column called "results" I can do:
#some_inspection = Inspection.first
#some_inspection.results
#=> {"assigned_to" => "John Smith", "inspection_date" => "2020_01_02", "passed" => "true"}
#some_inspection.results.keys
#=> ["assigned_to", "inspection_date", "passed"]
I was under the impression that the great thing about having a JSONB column is that it seamlessly translates for me. I don't have any attr_json nor any other specialized code in my model. Like so much Ruby and Rails "it just works". I pass it a hash and it stores that as JSON and when I ask for it, I get a hash. I can then do any hash methods like .values or .keys on it. If I need JSON back I can do #some_inspection.results.to_json.
If you pass it actual JSON then it will just store the JSON text as a string in the column. You can then get the JSON back just by calling the column name like:
#some_inspection.results
#=> "{\"assigned_to\":\"John Smith\",\"inspection_date\":\"2020_01_02\",\"passed\":\"true\"}"
But if you want to do something like .keys you have to parse it since it is a string:
JSON.parse(#some_inspection.results).keys
#=> ["assigned_to", "inspection_date", "passed"]
I'm using Rails 4.2 and using the .update_attributes method.
After some debugging it's come to my attention that if the field is MISSING from the params, Mongoid will just keep the old value of the param.
Edit: It seems that no matter what I do, the following code doesn't work:
campaign = Campaign.find_by username: params[:id]
campaign.update_attributes params[:campaign].permit!
Here's what does work:
campaign.attributes = params[:campaign].permit!
# .update_attributes(params[:camapign]) would likely work, too
campaign.allowed_brokers = params[:campaign][:allowed_brokers]
campaign.custom_payouts = params[:campaign][:custom_payouts]
campaign.save
Both allowed_brokers and custom_payouts are Array type fields. It seems that line 1 takes care of anything that's not an array field.
I'm 100% sure that incoming params don't contain the old values (in fact, they're missing from params[:campaign] - there's no params[:campaign][:allowed_bidders] for example.
Why is Mongoid not updating the array fields?
Thanks in advance.
PS: Here's the model:
class Campaign
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Attributes::Dynamic
field :name, type: String
# ==== Other irrelevant fields ====
# List of brokers and corresponding share %
field :custom_payouts, type: Array, default: []
# Taggable strings
field :allowed_brokers, type: Array, default: []
field :allowed_bidders, type: Array, default: []
field :can_start, type: Array, default: []
field :can_pause, type: Array, default: []
# Associations
has_and_belongs_to_many :bidders
end
PPS: I'm still trying to figure out why I have to manually amend the array fields. Meanwhile I've also found that despite the fact the fields are of type Array with a defined default of [], they can be set to null directly in the database which is bad. How do I avoid that? Maybe Attributes::Dynamic has something to do with that? If so, how'd I manually amend Arrays without it?
I have an model, say:
class MyModel <ActiveRecord::Base
attr_accessible :id, :name
end
I want to search this model using meta_search (https://github.com/ernie/meta_search),
How can I search by id or name?
I tried this but does not work:
MyModel.search(id_equals_or_name_contains: 'sample text')
The meta search document says they don't support different match type (https://github.com/ernie/meta_search#ored-conditions), so How should I achieve this?
Are you expecting the sample text to either be an integer or a string? If so you could implement a simple conditional using the function described here: Test if a string is basically an integer in quotes using Ruby?
s = 'sample text'
if !!(s =~ /^[-+]?[0-9]+$/)
MyModel.search(id_equals: s.to_i)
else
MyModel.search(name_contains: s)
end
I have the following array:
#unregistered_users = ['my#email.com', 'your#email.com', ...]
Now, I want to create a document for each array element:
#unregistered_users.each do |email_address|
Model.create(email: email_address, user: self.user, detail: self)
end
But it only creates a single document (the first element of the array). The other array elements are simply not created. Why?
We're using Ruby 1.9.3-p385, Rails 3.2.12, MongoID 3.0.0 and MongoDB 2.2.3
Update #1
So, we had a custom _id field with a custom random token using SecureRandom.hex(64).to_i(16).to_s(36)[0..127].
After I removed it worked normally, but with regular mongo ID's (which is not what we want).
Update #2
This is how the token are being generated:
class Model
include Mongoid::Document
include Mongoid::Timestamps
...
field :_id, default: SecureRandom.hex(64).to_i(16).to_s(36)[0..127]
...
index( { _id: 1 }, { unique: true } )
end
Try something like this to check what are the errors on the mongoid model:
#unregistered_users.each do |email_address|
model = Model.create(email: email_address, user: self.user, detail: self)
puts model.errors.inspect unless model.persisted?
end
or use create! to raise an exception and see what's happening
Assume:
The app name is "demo2"
The model was made off of a scaffold generation ("post")
Extra specifics in regards to which sub-folder I need to change to on the command line would be helpful.
Thanks!
You can do: Post.columns and then iterate on the resulting Array.
See more methods at Class: ActiveRecord::Base
Post.columns.each do |column|
puts "name: #{column.name}, type: #{column.type}"
end
in rails 4 its:
Post.column_names # => ["id", "title", ... ]