How can I hide show fields in Active Admin - ruby-on-rails-3

I am wondering if there is any way to hide fields in Active Admin on the show action or even not showing them if they are empty?

Sorted it in the .rb file for the resource -
show :title => :Company_Name do
panel "COMPANY DETAILS" do
attributes_table_for company, :Company_Name, :Title, :First_Name, :Surname, :Job_Title,:Direct_Number, :Contact_Email, :Address_1, :Address_2, :Address_3, :City, :Postcode, :Region, :Head_Office, :Showroom, :Trade_Counter, :Factory_Warehouse, :Telephone_Number, :Fax_Number, :Company_Email, :Web_Address, :PVCu_WindowsDoors_Method_1, :PVCu_WindowsDoors_System_1, :PVCu_WindowsDoors_Method_2, :PVCu_WindowsDoors_System_2, :Timber_Sash_Windows_Method, :FPW, :Composite_Doors_Method_1, :Composite_Doors_System_1, :Composite_Doors_Method_2, :Composite_Doors_System_2, :Composite_Doors_Method_3, :Composite_Doors_System_3, :Installer, :Trade, :Domestic, :Commercial, :New_Build
end
active_admin_comments
end

Just add a show blog with expected attributes in ActiveAdmin files, like following
show do
attributes_table do
row :id
row :title
row :created_at
row :updated_at
end
end

Related

Why isn't my search method working in Ruby on Rails?

In my Ruby on Rails application, I have a cinema system and am trying to return the screen a showing is in when a user searches for the showing.
To display the search drop down I am using this code in my _application.html.erb:
<%= render( :partial => '/screen_lookup', :locals => {:showings => #showings = Showing.all, :my_path => '/screens/display_screens_by_showing' })%>
Which renders the search from the _screen_lookup.html.erb:
<%= form_tag my_path, :method=>'post', :multipart => true do %>
<%= select_tag ('showings_id'),
options_from_collection_for_select(#showings, :id, :showing_times, 0 ),
:prompt => "Showings" %>
<%= submit_tag 'Search' %>
<% end %>
And uses the display_screens_by_showing in the screens_controller:
def display_screens_by_showing
#screens = Screen.showing_search(params[:showing_id])
if #screens.empty?
# assign a warning message to the flash hash to be displayed in
# the div "feedback-top"
flash.now[:alert] = "There are no films of that genre."
# return all products, in alphabetical order
#screens = Screen.all
end
render :action => "index"
end
And this searches using the method in the screen.rb model:
def self.showing_search(showing_id)
screen = Showing.where("id = ?", showing_id).screen_id
self.where("id = ?", screen)
end
Now, the problem I am having is that because a showing belongs_to a screen, and a screen has_many showings, I need to be able to search for the showing, and store that showing's screen_id in a variable to search for the screen that showing is in with, which I have tried doing in the model:
screen = Showing.where("id = ?", showing_id).screen_id
self.where("id = ?", screen)
But the error I am getting is:
NoMethodError in ScreensController#display_screens_by_showing
undefined method `screen_id' for #<ActiveRecord::Relation []>
These are the model relationships:
showing.rb:
class Showing < ActiveRecord::Base
belongs_to :screen
end
screen.rb:
class Screen < ActiveRecord::Base
has_many :showings
end
What code will get my search working?
The problem is that where doesn't return a record, it returns a relation that can be enumerated or chained, instead you want to use find or find_by to return a single record, which is kind equivalent to where + first
screen = Showing.find(showing_id).screen_id
which is sort of like doing
screen = Showing.where(id: showing_id).first.screen_id
If you want to pass a hash you can use find_by which will be like this
screen = Showing.find_by(id: showing_id).screen_id
PS:
I'm not sure what you're doing exactly, but i think those two lines can be merged into a single query ( not sure what it should be returning, but I'm assuming a screen )
def self.showing_search(showing_id)
Showing.find(showing_id).screen
end

Rails 3.2 - Validate in Model Based on Other Model Criteria

I have an AWARD model - there are two forms to create an AWARD. One is for nominating EMPLOYEES, the other is for Non-Employees. The EMPLOYEE form pulls a list of active employees to populate the Nominee selection box. The Non-Employee form has only text fields to populate the Nominee field (because I have no source to populate a selection list).
To dummy-proof the app, I want to run a validation that disallows Employees from using the Non-Employee form (because they will inevitably try to do so!). There is a hidden field on each form to set whether the form is Employee or Non: <%= f.hidden_field :employee, :value => true/false %>
So, on the Non-Employee form, if the user types in a nominee_username that exists in the Employee table, it should throw an error and direct them to the Employee form.
Here's what I've attempted:
class Award < ActiveRecord::Base
belongs_to :nominator, :class_name => 'Employee', :foreign_key => 'nominator_id'
belongs_to :nominee, :class_name => 'Employee', :foreign_key => 'nominee_id'
validate :employee_using_non_employee_form,
:on => :create, :unless => :employee_nomination?
def employee_nomination?
self.employee == true
end
def employee_using_non_employee_form
if nominee_username == employee.username ## -- this is where I'm getting errors. I get "undefined local variable or method employee for #<Award:.."
## I've also tried Employee.username, but get "undefined method username for #<Class..."
## Same error when I try nominee.username
errors.add(:nominator, "Please use Employee form.")
end
end
end
There is an association between the Award and Employee models, but I don't know how to call the Employee.username within the Award model to validate the Non-Employee form.
class Employee < ActiveRecord::Base
has_many :awards, :foreign_key => 'nominator_id'
has_many :awards, :foreign_key => 'nominee_id'
end
Try this for your validation method.
def employee_using_non_employee_form
if Employee.where(:username => nominee_username).present?
errors.add(:nominator, "Please use Employee form.")
end
end

Adding a top section in the index page of ActiveAdmin

I want to add some general information on active_admin top section.
For example, I want to render a partial at the top of the index page, so i can show something like
If I do it like I found in the documentation, It repeats for each element.
index do
render :partial=>'foo', :layout=>false
column :image_title
default_actions
end
I want to render :partial=>'foo', :layout=>false just ONCE.
Any help?
You can totally do this. You just might need to wrap it in an arbre component.
index do
panel "Foo", :id => "foo-panel" do
render :partial => "foo"
end
column :image_title
default_actions
end
class ::ActiveAdmin::Views::IndexAsAdminUser < ActiveAdmin::Views::IndexAsTable
def build(page_presenter, collection)
para "My custom text"
#or put _foo.html.erb to views/admin/admin_users
# render :partial=>'help', :layout=>false
super
end
end
ActiveAdmin.register AdminUser do
config.batch_actions = false
actions :index, :show
index as: :admin_user do #<---- as: :admin_user to load class ::ActiveAdmin::Views::IndexAsAdminUser
column :username
column :email
column :current_sign_in_at
column :last_sign_in_at
column :sign_in_count
default_actions
end
filter :username
end

Simple Form Association with Text Field

I have a Rails app that is using the simple_form gem. I have two models that are related, trades and stocks. In the form for trades, I want users to be able to enter their stock ticker symbol in a text field. Currently, I'm using the association function which renders a select box. The problem is that I want a text field instead since I have about a thousand stocks to choose from.
Is there a way I can do this (with or without Simple Form)?
the models:
class Trade < ActiveRecord::Base
belongs_to :stock
end
class Stock < ActiveRecord::Base
has_many :trades
end
the form on trades#new
<%= simple_form_for(#trade) do |f| %>
<%= f.association :stock %>
<% end %>
You should be able to just use this syntax:
<%= f.input :stock_id, :label => 'Enter your ticker:' %>
The problem here is that the user will not know what :stock_id is, as it's a reference to one of your many Stock objects.
So you probably want to implement a simple jquery autocomplete interface that returns a list of stocks like so:
[{:ticker => 'AAPL', :name => 'Apple Inc', :id => 1}, {:ticker => 'IBM', :name => 'International Business Machines', :id => 2}, etc ]
You can then display something like this as autocomplete results:
AAPL - Apple Inc
IBM - International Business Machines
and allow the user to select the one they are looking for. Behind the scenes you capture the :id and use that as your associated :stock_id.
You will need to add a stocks_controller action that takes a string and looks up Stocks based on a partial ticker and returns a max-number of stocks like 20.
def search
ticker_query = "%#{params[:ticker]}%"
stocks = Stock.where('ticker LIKE ?', ticker_query).limit(20)
render :json => stocks
end

Rails: Retrieving polymorphic data from nested model

I'm trying to retrieve data for all items from a box, a box can have compartments and I'd like to get all compartment info at the box level. items are made polymorphic as boxes won't necessarily have compartments.
MODEL
class Box < ActiveRecord::Base
has_many :compartments
has_many :items, :as => :itemable
end
In my Controller I can get results back with:
#box = Box.find(params[:id])
#itemable = #box.compartments.first
#itemable = #box.compartments.last
VIEW
<% #items.each do |item| %>
<%= item.name %>
<% end %>
but if I then try
#itemable = #box.compartments
OR
#itemable = #box.compartments.find(:all)
I get the error
undefined method `items' for #<ActiveRecord::Array>
OR
undefined method `items' for #<ActiveRecord::Relation>
Can anyone help with getting results back from all compartments?
So in compartments you have
belongs_to :box
has_many :items, :as => :itemable
Is this the case? #box.compartments should return an array of compartments right? It sounds like items is somehow getting called on #box.compartments somehow