Custom active admin page with index action - ruby-on-rails

I'm using rails 3, I have custom active admin page called "current_details",
I have created controller in the admin page:
ActiveAdmin.register_page "Current Details" do
controller do
def index
#milestones = Milestone.all
#collection = #milestones.select{|a| a.milestone_status == false}
#current_details = #collection.select{ |a| a.delivery_date.to_date.strftime('%m%Y') == Date.today.strftime('%m%Y') or a.delivery_date.to_date.strftime('%m%Y') < Date.today.strftime('%m%Y') }
end
end
content only: :index do
render 'index'
end
end
I need the index action for this, How do I get that?
I already tried with rendering partial, It's throwing error as: Missing partial admin/current_details/index.
I referred this
Any help would be appreciable.

make sure you have _index.html.erb file
views/admin/myname/_index.html.erb

Related

active admin how to render form on index page if object not created

I can't understand what I do wrong. My code won't work if subscription blank, but if I created it from rails c, all works fine...
# frozen_string_literal: true
ActiveAdmin.register Subscription do
actions :index
index do
result = Subscriptions::GetPricing.call(admin: current_admin)
if result.success?
render partial: 'subscription_form', locals: { amount: result.plan.amount }
else
flash[:alert] = result.message
render partial: 'subscription_errors'
end
end
end
Now i get: There are no Subscriptions yet. simple message.
And i want left all styles, nav panel, etc how it default, but in container should be store my code from partials.
If your intent is to display an input form if the table is unpopulated then try this:
controller do
def index
collection.size == 0 ? redirect_to(new_subscription_path) : super
end
end
I think what you are trying to do is a bit wrong. index do block is to render the view level mainly. If you want to override controller action you will have to do it like below -
controller do
def index
# your code here
end
end
Have a look at the documentation -
https://activeadmin.info/8-custom-actions.html
https://activeadmin.info/3-index-pages.html

Rails: How to review content before submit/save?

I know it is simple but I can't get my head around a solution.
It is a job board site. Lets say it's functionality similar to this site. When a user fill all required information and click "To next step" or "Preview", another page loads with all filled data. That page is similar to the final page when data is saved.
When user on preview page, it can go forward and submit the page (in this case it will be saved to DB). Or, click back to Edit the job.
I tried the following::
Within _form.html.erb I added a preview button
<%= f.submit "Preview", :name => 'preview' %>
Within JobControllers I altered create method
def create
if params[:preview]
#job = Job.new(jobs_params)
render 'jobs/preview'
else
#job.save
end
end
Created a Preview view /jobs/preview.html.erb
Now I have 2 problems.
1- Within my preview page, I have an edit button like so: <%= link_to "Edit Job", edit_job_path(#job) %>. But I have an error because I can't find #job. Error says: No route matches {:action=>"edit", :controller=>"jobs", :id=>nil} missing required keys: [:id]
SOLUTION Changed like to <%= link_to 'Back to edit', 'javascript:history.go(-1);' %>
2- How I would submit and add to my DB all information on preview page?
Thank you.
Once I've given a similar task. What I've done is to save records, but not to publish. In my index (resource listing) action of relevant controller, I only fetch published records. Also show action prechecks if that record's published attribute is set to true.
What was my model/controllers looked like before
#model
class Book < ActiveRecord::Base
...
scope :active, -> { where(published: true).some_other_queries }
self.active?
(published && some_other_requirements)
end
...
end
#controller
def index
#books = Book.active
...
end
def show
if #book.active?
render 'show'
...
else
...
end
end
First added a secret key for previews.
#model
def secret
#some custom random key generation
# e.g. Digest::MD5.hexdigest("#{id}_#{ENV['RAILS_SECRET']}")
end
Then added preview action to controller
def preview
# i don't check if the record is active.
# also added a security layer, to prevent irrelevant guys to view
# that record
if #book.secret == params[:secret]
render 'show'
else
...
end
end
In dashboard
...
= link_to "Preview", preview_book_path(book, secret: book.secret)
...
then added a member route
#routes
resources :books do
get :preview, on: :member
end
When I have to do something like this what I normally do is create a review table in my app. This table looks just like the table that is going to saving to.
When they press the "Approved" or "Save" button just populate the new table with the proper data.
I like to create a routes to handle this
resources :something do
match 'move_to_something_else' => 'somethings#move_to_something_else', as: :move_to_something_else, via: :all
end
Now on the controller we can do the following:
def move_to_something_else
#something = Something.find(params[:id])
#something_else = SomethingElse.new
#something_else.name = #something.name
....
#something_else.save
redirect_to something_else_path(#something_else)
end
Alternative you could add a state to your table with the default value of 'draft'
# config/routes.rb
resources :something do
match 'published' => 'somethings#published', as: :published, via: :all
end
# Controller
def published
#something = Something.find(params[:id])
#something.state = 'published'
#something.save
redirect_to something_path(#something)
end

How to display Devise account details on a profile page

Using Devise I would like to display User account information such as profile name, first & last name etc on another page called profile page within my rails application.
I have created a controller called profiles with a view called profile/show
In the controller have added the below code
def show
#user = User.find_by_profile_name(params[:id])
if #user
render action: :show
else
render file: 'public/404', status: 404, formats: [:html]
end
end
end
In the view profiles/show I have the following code
<%= #user.profile_name %>
and the route is get 'profiles/show'.
My issue is when I do all of the above the profile name of the user still does not display on the profile page? There are no errors that come up it just doesn't display. I am not sure what code I am missing. I have checked the console and the user does have a profile name save to that ID and this is also in the devise account settings. So I am not sure how to get this information to display?
In Rails you would usually set it up like follow to take leverage of convention over configuration:
# config/routes.rb
resources :users, only: [:show, :index]
# app/models/user.rb
class User < ActiveRecord::Base
# ...
def self.find_by_uid!(uid)
User.find_by!("profile_name = :p OR id = :p", p: uid)
end
end
# app/controllers/users_controller.rb
class UsersController
# GET /users/:id
def show
#user = User.find_by_uid!(params[:id])
# Rails does the magic.
end
# GET /users
def index
#users = User.all
end
end
<%- # app/views/users/show.html.erb -%>
<h1><%= #user.profile_name %></h1>
The only special part here is that in the user model we create a class method which will query by id or profile_name. The reason that this is important is that it lets you use link_to(#user) and redirect_to(#user) as expected.
Which is also why we use resources :users. When the route name and the model line up the Rails polymorphic route handlers are able to do their job. If you want to use /profiles thats fine but never /profiles/show - including the action in the route defeats the whole purpose of REST.
The show action will render users/show.html.erb by default. So you rarely need to explicitly render in your controller.
render action: :foo
is only used when you want to render a template with the same name as another action, its usually used as follows:
def create
#something = Something.new
if #something.save
redirect_to(#something)
else
render action: :new # renders views/something/new.html.erb
end
end
If you want to explicitly render a template you would do render :foo or render "foo/bar".
And when you use find or find_by! it will raise an exception if the record is not found which by default will render the static 404 template. Reproducing this error handling in your actions is not very desirable since it violates the DRY pinciple.

Rails Set Layout Based on URL Params

So I am trying to change the layout of a view based on url params.
So far, I figured out I have to set the layout in the controller. In my controller under the show action I have:
if params['iframe'] == 'true'
render :layout => 'vendored'
end
The layout 'vendored' exists in views/layouts. I am getting the dreaded rendering multiple times. Here is the rest of the show action in my controller:
def show
#event = Event.find(params[:id])
#user = current_user
#approved_employers = current_user.get_employers_approving_event(#event) if user_signed_in?
respond_with(#event)
The problem is that I don't see another render. I don't see another one in the entire controller. Of course, there is a render somewhere because it is rendering my default application layout, is that causing the problem? I read in the rails docs that I can add
and return
to the end and that should fix the problem, but not sure where to put that since the two renders are not next to each other. I also don't see any other redirect_to's either. Where should I be looking for this other render? Is that the problem?
Alternatively, I think this is easier to understand:
class YourController < ApplicationController
layout :iframe_layout
private
def iframe_layout
params['iframe'] ? "vendored" : "application"
end
end
See this answer. For your case:
before_filter :set_layout, :only => [:show]
private
def set_layout
self.class.layout ( params['iframe'] == 'true' ? 'vendored' : 'application')
end

ActiveAdmin action items depending on status of data

I want to hide the edit path if the object to edit has a certain status.
How can I do that?
I finally did it. I needed two things:
Redirect when access directly and hide buttons to the edit page.
To redirect when the user try to access directly to the edit page I use a before_filter:
before_filter :some_method, :only => [:edit, :update]
def some_method
redirect_to action: :show if status == something
end
To hide the buttons I do it like this:
ActiveAdmin.register Model do
config.clear_action_items!
action_item :only => [:show] , :if => proc { instance.status == something } do
link_to 'Edit', edit_model_path(instance)
end
end
If you are talking about hiding the edit link that is shown by default (along with the view and delete links) in the index action, you can customize the index view as follows:
ActiveAdmin.register Model do
index do
column :actions do |object|
raw( %(#{link_to "View", [:admin, object]}
#{link_to "Delete", [:admin, object], method: :delete}
#{(link_to"Edit", [:edit, :admin, object]) if object.status? }) )
end
end
end
Because the content of the column will be only what is returned by the column block, you need to return all three (or two) links at once as a string. Here raw is used so that the actual links will be displayed and not the html for the links.
This can be achieve using the following:
ActiveAdmin.register Object do
index do
column :name
actions defaults: true do |object|
link_to 'Archive', archive_admin_post_path(post) if object.status?
end
end
end
Note that using defaults: true will append your custom action to active admin default actions.
You could create a before_filter in your controller that only applies to edit action. It could check the status, and allow it to run or redirect_to depending on the return of the method.
Something like this in your applications controller:
def some_method
if foo.bar == true
redirect_to foos_path
end
end
Then in the beginning of your controller of question
before_filter :some_method, :only => :edit
A fully customizable solution would be to use an authorization adapter, either a custom one or a library such as pundit or cancan: https://activeadmin.info/13-authorization-adapter.html
My use case was around restricting actions based on the context (e.g. the user editing). I solved it locally like this:
controller do
def action_methods
if condition?
super
else
super - ['edit', 'update']
end
end
end
if u want to hide the "edit" link (in active_admin views) for object if the object holds some specific value, u can override the default view for the method and add condition before the link is displayed.

Resources