Search by id in Administrate Gem in Rails - ruby-on-rails

By default Administrate Gem gives us a feature where we can search record by name. But now I am trying to search record by ID in search bar of admin Dashboard, like this
ATTRIBUTE_TYPES = {
id: Field::Number,
name: Field::String,
}.freeze
But I am not able to search records by its ID, I try this but didn't work
ATTRIBUTE_TYPES = {
id: Field::Number.with_options(searchable: true),
name: Field::String,
}.freeze
I am expecting to serach records by two things, like ID and Name also

Related

How do I define products with only specific property tags (Spree, Rails)

I've got a custom Spree app. I need to query Spree::Products that have the associated Spree::Property
I have a 'property' with the name "Rating" on only certain products, but I can't query those products correctly. What I have now is:
Spree::Product.joins(:properties).where(:property_name.downcase == "rating")
but that just pulls all the products that have any :properties associated with them at all.
Spree::Property -
Spree::Property(id: integer, name: string, presentation: string, created_at: datetime, updated_at: datetime)
Just tested on Spree 3.1. You can do that from Product or Property model.
Spree::Product.joins(:properties).where(spree_properties: {name: "rating"})
or
Spree::Property.where(name: "rating").first.products
*You have to modify the code to use downcase string.

Rails app not recognizing active record entries?

I am building a rails app and have create a basic and pro plan in database, here is output of Plan.all from rails console:
=> #<ActiveRecord::Relation [#<Plan id: 1, name: "basic", price: #<BigDecimal:7f9aad0bf578,'0.0',9(27)>, created_at: "2016-11-03 04:21:55", updated_at: "2016-11-03 04:21:55">, #<Plan id: 2, name: "pro", price: #<BigDecimal:7f9aad0be448,'0.1E2',9(27)>, created_at: "2016-11-03 04:22:21", updated_at: "2016-11-03 04:22:21">]>
When I create a user under either plan i get this error:
1 error prohibited this user from being saved: Plan must exist
Not sure why it is not picking up the plans.
The error "Plan must exist" when you create a user means that whatever plan_id you gave to the user does not match up with the id of an actual plan in the database. Check the plans you have created, look a their ids, and make sure the plan_id you give to your user matches the id of one of those plans.
Note: it is not enough to create database tables for each of the 2 types of plans, you must create actual instances of the plans.
Also: check to make sure you has_many / belongs_to relationship is set up correctly.

FactoryGirl rspec, while creating multiple factories at once

When I am creating multiple object of Factory using method create_list, the order and where method don't work on it because create_list creates the array of factory objects.
users = FactoryGirl.create_list(:user, 5)
users.order('name ASC')
It gives undefined method order for Array
So, what should I do to create the multiple factory objects inside the ActiveRecord Collection?
The order and where methods are not defined on Array but on ActiveRecord::Relation. It's the kind of thing that gets passed around by the ActiveRecord query interface. You simply cannot run a query on an array. To run a query you need to start from scratch:
create_list, :user, 5
users = User.where(...).order(name: :asc)
But you might as well directly pass your arguments to create_list so that the condition is satisfied without needing to re-select the users. I also often find myself writing arrays explicitly when I need to alter values in each row e. g.
users = [
create(:user, name: 'Alfred'),
create(:user, name: 'Bob'),
create(:user, name: 'Charlie'),
create(:user, name: 'David'),
create(:user, name: 'Egon')
]
The users are already ordered by name and you're good to go. If you have some condition in the where clause that for example separates the users in two groups, you can just go ahead and separate these users directly. For example imagine we have an admin flag in the users table and you want to create many users, some being admins and some not. Then you'd do
admins = [
create(:user, name: 'Alfred', admin: true),
create(:user, name: 'Charlie', admin: true),
create(:user, name: 'Egon', admin: true)
]
visitors = [
create(:user, name: 'Bob'),
create(:user, name: 'David')
]
No need to query at all. Of course you can also do that in let syntax if you like.

Categories and subcategories with seeds.rb

I have a form and want to be able to select category & subcategory.
This is an automatic example from seeds.rb:
Examples:
cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
Mayor.create(name: 'Emanuel', city: cities.first)
There is cities.first - but can you do it for cities.sixth or cities.twelfth...?
Is there a different way to do it and connect subcategories with categories in the file?
I would personally advise against using positions to assign subcategories. The possibility exists that there is data on another devs machine or a server.
I generally do it something like:
city = City.find_or_create_by_name(
name: "Chicago"
)
mayor = Mayor.find_or_create_by_city_id(
city_id: city.id,
name: 'Emanuel')

Deleting records from HABTM association

I'm trying to do something fairly simple. I have two models, User and Group. For simplicity's sake, let's say they look like this:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
and
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
Now, for some reason, I have a user that has the same group twice. In the Rails Console:
user = User.find(1000)
=> #<User id: 1000, first_name: "John", last_name: "Doe", active: true, created_at:
"2013-01-02 16:52:36", updated_at: "2013-06-17 16:21:09">
groups = user.groups
=> [#<Group id: 1, name: "student", is_active: true, created_at: "2012-12-24 15:08:59",
updated_at: "2012-12-24 15:08:59">, #<Group id: 1, name: "student", is_active: true,
created_at: "2012-12-24 15:08:59", updated_at: "2012-12-24 15:08:59">]
user.groups = groups.uniq
=> [#<Group id: 1, name: "student", is_active: true, created_at: "2012-12-24 15:08:59",
updated_at: "2012-12-24 15:08:59">]
user.save
=> true
And there is some SQL output that I've silenced. I would think that everything should be all set, but it's not. The groups aren't updated, and that user still has both. I could go into the join table and manually remove the duplicates, but that seems cludgy and gross and unnecessary. What am I doing wrong here?
I'm running Rails 3.2.11 and Ruby 1.9.3p392
Additional note: I've tried this many different ways, including using user.update_attributes, and using group_ids instead of the groups themselves, to no avail.
The reason this doesn't work is because ActiveRecord isn't handling the invalid state of duplicates in the habtm association (or any CollectionAssociation for that matter). Any ids not included in the newly assigned array are deleted - but there aren't any in this case. The relevant code:
# From lib/active_record/associations/collection_association.rb
def replace_records(new_target, original_target)
delete(target - new_target)
unless concat(new_target - target)
#target = original_target
raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \
"new records could not be saved."
end
target
end
The 'targets' being passed around are Arrays of assigned records. Note the call to delete(target - new_target) is equivalent in your case to delete(user.groups - user.groups.uniq) which results in an empty Array passed (since comparison is based on the id attribute of each record).
Instead, you'll need to clear out the association and then reassign the single group again:
group = user.groups.first
user.groups.clear
user.groups << group
This might be a way to cleanup those duplicates (it handles any number of groups of duplicate associations):
user = User.find(1000)
user.groups << user.groups.group_by(&:id).values.find_all {|v| v.size > 1}.each {|duplicates| duplicates.uniq_by! {|obj| obj.id}}.flatten.each {|duplicate| user.groups.delete(duplicate)}

Resources