Active Admin Errors - ruby-on-rails

I am using active admin for the first time, and I don't know much about it. I'm trying to create a table (in admin dashboard view) that shows certain details of the model object (which are created via form submission.)
I simply want to be able to view recent additions to the model object from the admin dashboard.
I've read the documentation on Active Admin, but it seems like most of it is using examples that don't entirely meet what I'm trying to do. (Or it could just be that I am a newbie at this)
I've looked at a few forums and found some examples, but even they use multiple variations on the table_for method.
I am getting this error:
NoMethodError in Admin::Dashboard#index Showing
C:/Ruby24-x64/lib/ruby/gems/2.4.0/gems/activeadmin-1.4.3/app/views/active_admin/page/index.html.arb
where line #2 raised:
undefined method `first_name' for # Did you
mean? sti_name
Any insight or advice would be appreciated. I've posted my code from dashboard.rb below:
ActiveAdmin.register_page "Dashboard" do content :title => proc{ I18n.t("active_admin.dashboard") } do columns do column do
panel "New Teacher Applicants" do
table_for Volunteer do |t|
t.column("Name") { |volunteer| volunteer.first_name }
t.column("Surname") { |volunteer| volunteer.last_name }
t.column("Email") { |volunteer| volunteer.email }
t.column("Gender") { |volunteer| volunteer.gender }
end
end end end
end end

I think this is what you are looking for:
panel 'New Teacher Applicants' do
table_for Volunteer.order("created_at desc").take(5) do
column "Name", :first_name
column "Surname", :last_name
column "Email", :email
column "Gender", :gender
end
end
The argument to table_for should be a collection. Maybe take a closer look: https://activeadmin.info/12-arbre-components.html#table-for

Related

How do I call the name of a user when they belong to a model

I have two models, Chasing and User, a chasing belongs_to :user and a user has_many :chasings.
I created a migration for linking the two models together:
class AddUsersToChasings < ActiveRecord::Migration
def change
add_reference :chasings, :user, index: true, foreign_key: true
end
end
I have a controller for creating new users which I then want to be able to assign to chasings. I currently have this code in my chasings form for selecting the user:
<%= f.select :user_id, options_for_select(User.all.map {|c| [c.name, c.id]}), { :include_blank => "Please select user"}, {:class => "form-control"} %>
This seems to do the trick, after calling Chasing.first in rails console I can see the chasing now has user_id relevant to the user I picked. I can also run Chasing.first.user.name to give me the name of the user who is associated with the chasing. I'm wanting to show this name in my index view, the code I currently have for this is:
ChasingsController:
def index
#chasing = Chasing.all
end
Index view:
<% #chasing.each do |chasing| %>
<%= chasing.user %>
<% end %>
This shows a random string (seems to change every time I update a chasing - #<User:0xf5b0ba8> for example). when I change this to chasing.user.name I get 'undefined method `name' for nil:NilClass'.
Is there a way I can call the name for my view?
EDIT:
As per NickM's comment below I had chasings without users assigned to them causing active record to throw the error.
Looks like you have some Chasing objects in your database without user_ids. You can test by doing <%= chasing.user.name if chasing.user %>

How to set some default values in a column in rails

I'm developing an 'expense manager' app which helps the users to manage their expenses and generate reports with Graphs and also they can get the expenses sorted by date or by period of time.
A user can login add expenses and select a category for each expense from a dropdown.
Upto here everything went well, But I was stuck with a doubt if there is any possibility to add some default categories in the categories table when the user sign up. I also have a requirement for the user to delete these default categories which should not effect other users categories.
Please suggest me an idea how we can deal with this requirement instead of using Seed data.
Migration for creating categories
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.timestamps null: false
end
end
end
Category drop down in expense new form
<div class="form-group">
<%= f.label :category, "Category:" %><br>
<div class="col-md-2">
<%= f.collection_select(:category_id, current_user.categories, :id, :name, {}, { :class => "select_box selectpicker picker"}) %>
</div>
</div>
Git repository of this app: https://github.com/atchyut-re/expense_manager
Hope I'm clear if I need to give any further details please mention in comment.
Create a after_create callback in your user model to create some categories. As the categories are user dependent, then there should be an association between user & categories.
You can simply use rails call back to create the default categories for every user, the code will be like:
class User < ActiveRecord::Base
before_create :create_default_categories
DEFAULT_CATEGORIES = [
{name: 'default name 1', other_attribute: 'default other attribute 1'},
{name: 'default name 2', other_attribute: 'default other attribute 2'}
]
def create_default_categories
DEFAULT_CATEGORIES.each do |default_attrs|
self.categories.build(default_attrs)
end
end
end
So when user was created, the default categories would be created as well!

Ruby on Rails: Nested Model Form Checkbox For A 'has_many :through' Relationship

Still fairly new to RoR, let alone Ruby itself.
Here's my issue. I'm using Rails 4 and Ruby 2.1.0
I have a User class with this relationship:
has_many :roles, ->{ uniq }, :through => :user_roles
accepts_nested_attributes_for :roles
Now, the table 'roles' simply has a list of roles, such as 'admin', 'moderator', 'visitor', 'artist', etc.
The table 'user_roles', is just a relational table, with the role's key and the user's key.
So, to clarify, 'users' has a one to many relationship with 'user_roles' and "user_roles' table has a many to one relationship with the 'roles' table.
Something like this:
users: id, name, email #ie: 12, 'mikey', 'mike#foobar.com'
user_roles: id, user_id, role_id #ie: 4324, 12, 8
roles: id, name, weight #ie: 8, 'moderator', 11
I've been given the task of adding a checkbox toggle in the admin section so that an admin can grant the moderator role to any one user.
Each admin page is for one specific user. Therefore, the form_for is based on the #user instance, depending on which user the admin selected for editing.
RailsCasts #196 kind of helped me understand the concept, but it's platform is just different enough that I'm not sure how to exactly translate it into what I need. Likewise, there are some similar questions here on StackOverflow as well - but again, I can't seem to get it to translate correctly into my situation.
What I do have, I think should be at least somewhere in the realm of the right direction. THen again, maybe I'm way off. Here is my form code:
= form_for #user, :url => admin_user_path(#user), html:{class: 'form_horizontal'} do |f|
%br
%h4{class: :dc_green}Logistical Information
= f.label :display_name, "Display Name"
= f.text_field :display_name
= f.label :email, "eMail"
= f.text_field :email
%br
= f.fields_for :roles do |a|
= a.check_box :moderator, { inline_label: :none }
= a.label :moderator, {for: :moderator, class: "checkbox inline"}
%br
The error I'm getting with this form code is: undefined method `moderator'
Thank you in advance for anyone who can offer support :)
I guess I should probably add that I'm also clueless as to how I should handle this in the controller once it is submitted. But, first things first.
UPDATE
So, the reason I'm getting the undefined error is because it doesn't exist for that user. Which is bad. I need to be able to add the role to the user or remove the role. However, the only roles coming through are the roles the user has already been assigned to. So I'm totally doing this wrong. Now I'm really in the dark.

Active admin shows html code

I'm using ejholmes Active_admin Editor and it's working fine but in my active admin index I see the html code with tags and not the correct output. I do use .html_safe in my views but here's my active admin's posts.rb
...
index.do
column :id
column "Titolo", :title
column "Corpo news", :body
column "Creato il", :created_at
column "Modificato il", :updated_at
column :link
column "Link Immagine", :image_url
bool_column :attivo
default_actions
end
...
I want to have my "Corpo news" column rendered.
Thanks for the help!
I guess you need to use the method .to_html as you can see by the source
So in the view you need to call
body.to_html

Cannot retrieve lookup values correctly

I've built a lookup table in my Rails application.
It is a table that stores lookup text values for drop-down pickers or possibly check boxes. I want the lookup table to have a view associated so the values can be easily edited. I also may want to share lookup values among multiple models for a single field in the future.
So far I've managed to get it to work for the selection of values, but then displaying the text value again on a show or index view has been problematic.
This is how I built the lookup table
rails g scaffold Lookup field_name lookup_text table_name note
In the edit.html.erb where there is a lookup on a field, I've got code like this, which works and allows me to pick from a list.
<div class="field">
<%= f.label :status %><br />
<%= f.collection_select :status, Lookup.find(:all,:conditions => ["table_name = 'course' and field_name = 'status'"]), :id, :lookup_text, include_blank: true,:prompt => "Status" %>
</div>
That all works fine. When I try to display it back I cannot find the correct syntax. The best I have found is this:
(in the controller)
#status = Lookup.where(:id => #course.status).pluck(:lookup_text)
(in the view)
<p>
<b>Status:</b>
<%= #status %>
</p>
I think I am getting the entire object. It displays like this:
Status: ["Active"]
My questions are:
(1) How do I display the value only?
(2) Is this the best approach?
I've had a look at these and other SO questions, but none are really what I am looking for:
Rails Polymorphic with Lookup Table
Implementing a lookup table in Rails
EDIT
OK this works, but it doesn't look like it is the correct solution. Has anyone got a better way of doing this?
#status = Lookup.where(:id => #course.status).pluck(:lookup_text)[0]
Just another way to show the value is #status = Lookup.find(#course.status).lookup_text
Why not to try use classes for different lookups:
class CourseStatus < ActiveRecord::Base
set_table_name "lookups"
default_scope where("table_name = 'course' and field_name = 'status'")
end
class Course
belongs_to :course_status
end
You then can use:
CourseStatus.all # e.g. to fill select options
Course.first.course_status.lookup_text # => "Active" or smth else
Or without classes:
class Lookup
def self._by_table_and_field(table, field)
['table_name = ? and field_name = ?', table, field]
end
scope :by_table_and_field, lambda { |table, field|
where(Lookup._by_table_and_field(table, field))
}
end
class Course
belongs_to :status, class_name: 'Lookup', conditions: Lookup._by_table_and_field('course', 'status')
end
Lookup.by_table_and_field('course', 'status').all
Course.first.status.lookup_text

Resources