Formating Active admin table data with a function - ruby-on-rails-3

i have a resource defined for active admin like so. All I want to do is format the phone with the rails *number_to_phone* function. However either the documentation is not clear, or my still limited ruby/rails vocabulary is lacking the proper term.
ActiveAdmin.register Voter do
menu :label => "Voters"
index do
column :id
column :last_name
column :first_name
column :middle_name
column :suffix
column :address
column :city
column :state
column :zip
column :zip4
column :phone
end
end

per Rails Cast #284
column :phone, :phone do |voter|
number_to_phone voter.phone
end

Related

Active Record object based on group by count

Hi I am ROR developer and using rails 3.2.13 with Postgres database.
I have two models:
Question
attr_accessible :category, :is_active, :question_text, :question_type_id, :survey_id,
:user_id
has_many :abusive_questions
And
AbusiveQuestion
attr_accessible :question_id, :user_id, :ipaddress, :posted_by
belongs_to :question
From this I want to get the AbusiveQuestion which count is greater than a particular value (ex: 5).
I did the following from my rails command
AbusiveQuestion.count(:group=>"abusive_questions.question_id")
and got
=> {1=>1, 5=>3, 3=>1}
For this result, the key is the question_id and value is the count but, I want to get the question which value is greater then a particular dynamic value (for ex:2).
Please help me.
I think you'll want to join Question on AbusiveQuestion then use a select and having to get what you want.
Something like:
AbusiveQuestion.select('abusive_questions.*, count(question.id) as question_count').
joins(:questions).
group('abusive_questions.question_id').
having('count(abusive_questions.question_id) > 5')
You can use having method.
http://guides.rubyonrails.org/active_record_querying.html#having
x = YOUR_DYNAMIC_COUNT
AbusiveQuestion.group(:question_id).having("count_all > ?", x).count

Rails 4 Generating Invalid Column Names

I have a fairly simple query to return the first record in a many-to-many relation or create one if it doesn't exist.
UserCategorization.where(category_id: 3, user_id: 5).first_or_create
My model looks like:
class UserCategorization < ActiveRecord::Base
belongs_to :user
belongs_to :category
self.primary_key = [:user_id, :category_id]
end
However it generates an invalid column name in the SQL:
SQLite3::SQLException: no such column: user_categorizations.[:user_id, :category_id]:
SELECT "user_categorizations".* FROM "user_categorizations" WHERE
"user_categorizations"."category_id" = 3 AND "user_categorizations"."user_id" = 5
ORDER BY "user_categorizations"."[:user_id, :category_id]" ASC LIMIT 1
If I remove self.primary_key = [:user_id, :category_id] from the model, it can retrieve the record correctly but cannot save because it doesn't know what to use in the WHERE clause:
SQLite3::SQLException: no such column: user_categorizations.:
UPDATE "user_categorizations" SET "score" = ?
WHERE "user_categorizations"."" IS NULL
Has anyone seen this before?
I think one of these two suggestions will work:
First, try adding the following migration:
add_index :user_categorizations, [:user_id, :category_id]
Make sure to keep self.primary_key = [:user_id, :category_id] in your UserCategorization model.
If that doesn't work, destroy the UserCategorization table and run this migration:
def change
create_table :user_categorizations do |t|
t.references :user
t.references :category
t.timestamps
end
end
references are new to Rails 4. They add a foreign key and index to the specified columns.
Good Luck!
So it looks like Rails 4 ActiveRecord doesn't do composite keys very well so many-to-many models create the issues above. I fixed it by using this extension to ActiveRecord: http://compositekeys.rubyforge.org/

Rails form select with NULL (no choice) support

How can I add a NULL option to my form select? I have a table:
categories
id
category_id
name
If I'm creating a new category, I want to be able to select the NO_CATEGORY option (NULL value and id).
My view code:
<%= f.collection_select :supercategory_id, Category.all, :id , :name %>
Also, it is a good idea? Isn't it better to have some predefined ROOT category in the database? Thank you.
Try:
<%= f.collection_select :supercategory_id, Category.all, :id , :name, :include_blank => true %>
Its ok to have null. Just have your model logic know that it should create a new category and assign it rather than mass assign from the select. Might be something that happens in a before_validation method

Efficient query for distinct count and group with two columns

Given a simple model that consists of descriptions, tags, and some other fields
The results should be:
a list of all tags in Entry.all without duplicates (e.g. Entry.select("DISTINCT(tag)") )
the number of duplicates for each tag, also used to sort tags
all descriptions for each tag sorted alphabetically, again without duplicates (however, the exactly same description can exist with a different tag)
Is it possible to combine this in one (efficient) query?
Edit:
def change
create_table :entries do |t|
t.datetime :datum, :null => false
t.string :description
t.string :tag
(and some others)
end
add_index :entries, :user_id
end
It's better to create additional table:
rails g model Tag name:string description:string
rails g model Entry tag:references ...
And then just call them:
#entries = Entry.select('tag_id, count(tag_id) as total').group(:tag_id).includes(:tag)
After that, you will have all descriptions in your object:
#entries.first.tag.description # description of entry tag
#entries.first.tag.total # total number of such kind of tags
P.S.: Why just one tag per entry?

How to validate uniqueness in Rails 3 Model if I want to check if there is a 2-field combination?

I want to know if there is a way in Rails 3, in which I can validate the uniqueness of 2 fields that goes in combination.
The logic goes this way:
I have two fields employee_code and date_entry.
Case 1: If the employee_code and date_entry combination already exist it won't allow to save another record with the same employee_code and date_entry.
Case 2: If the employee_code and date_entry exists but not on the same record, it will allow to save the field.
validates_uniqueness_of :employee_code, :scope => [:date_entry]
Three and more columns, all you need to do is add elements to the scope list:
validates_uniqueness_of :employee_code, :scope => [:date_entry, :another_column]
or Rails 3:
validates :employee_code, :uniqueness => {:scope => :date_entry}
This is for Rails 3:
To do this with just 2 columns, you can just do something like:
validates :empcode, :uniqueness => {:scope => :date_entry}
For more than 2 columns you can do something like:
validates :empcode, :uniqueness => {:scope => [:date_entry, :description]}