I am using ActiveAdmin on my Rails project. I use Draper as decorator but I don't understand why the show view is not decorated. According to the documentation it should be working just adding the decorate_with MyDecorator in my ActiveAdmin resource.
Here is my code:
ActiveAdmin.register Home do
...
decorate_with HomeDecorator
show do
attributes_table do # not being decorated
row :content
row :status
row :image
row :author_with_avatar
end
end
end
Does someone know what is wrong with my code ?
When I've run into this problem, it's because I've customized the controller's find_resource method. In that case be sure to return a manually decorated object:
def find_resource
MyModel.find_by_some_unique_finder(params[:id]).decorate
end
If all else fails you can force it using this approach:
show
attributes_table_for model.decorate do
row :decorator_method
row(:custom_label) { |m| m.decorator_method }
See http://activeadmin.info/docs/6-show-pages.html for more details
Related
I am making this simple ApplescriptObjC cocoa app just as an exercise for me to understand the multi treading, it is a text field and a label, I was trying to update the label in real time while typing in the text field, but it only get updated once I press enter but not in real time, any idea how I can make that work? here is the code.
Thanks
script AppDelegate
property parent : class "NSObject"
property prgLabel: missing value
property subjectFeild: missing value
on applicationWillFinishLaunching_(aNotification)
-- Insert code here to initialize your application before any files are opened
activate
end applicationWillFinishLaunching_
on applicationShouldTerminate_(sender)
-- Insert code here to do any housekeeping before your application quits
return current application's NSTerminateNow
end applicationShouldTerminate_
on textChange_(sender)
set SU to subjectFeild's stringValue() as string
prgLabel's setStringValue_(SU)
end textChange_
end script
1) Set the delegate of the textfield to be your app delegate.
2) Implement controlTextDidChange, which is called every time the text field changes during editing.
script AppDelegate
property parent : class "NSObject"
-- IBOutlets
property theWindow : missing value
property prgLabel: missing value
property subjectFeild: missing value
on applicationWillFinishLaunching:aNotification
subjectFeild's setDelegate:me
end applicationWillFinishLaunching_
on controlTextDidChange:notification
prgLabel's setStringValue:subjectFeild's stringValue()
end
end script
I have created an XPage with the following: Started by creating a custom layout control using the Application Layout. I aded the layout control to the xpage and then dropped in a Dynamic Content Control. I configured the control as follows:
<xe:dynamicContent id="dynamicContent1" defaultFacet="GovernanceReviews"
useHash="true">
<xp:this.facets>
<xc:ccViewDocumentTemplates xp:key="DocumentTemplates"></xc:ccViewDocumentTemplates>
<xc:ccViewGovProcurementReviews xp:key="GovProcurementReviews"></xc:ccViewGovProcurementReviews>
<xc:ccViewGovRevReporting xp:key="GovRevReporting"></xc:ccViewGovRevReporting>
<xc:ccViewGovRevWOCompleted xp:key="GovRevWOCompleted"></xc:ccViewGovRevWOCompleted>
<xc:ccViewGovernanceReviews xp:key="GovernanceReviews"></xc:ccViewGovernanceReviews>
<xc:ccViewProfilesByType xp:key="ProfilesByType"></xc:ccViewProfilesByType>
<xc:ccViewProfilesWithTargetCompl xp:key="ProfilesWithTargetCompl"></xc:ccViewProfilesWithTargetCompl>
<xc:ccViewLastUpdated xp:key="LastUpdated"></xc:ccViewLastUpdated>
<xc:ccViewUserGuide xp:key="UserGuide"></xc:ccViewUserGuide>
<xc:ccViewTracking xp:key="Tracking"></xc:ccViewTracking>
</xp:this.facets>
</xe:dynamicContent>
Then I dropped in a navigator control in the left column and created BasicLeafNodes to correspond to the dynamic content control I used the href property and used the #content="" to display the correct content.
This works just fine, but I am having problems figuring out how to make the selections in the navigator highlight when they are selected. I know I need to compute the Selectd property,but I can't figure out how to get the xp:key value so I can compare it to the SubmitValue. I know this is probably something simple, but I can't figure it out.
Can someone please enlighten me.
Thanks,
MJ
ADDED 03/26/2014 - I have a feeling that it has something to do with Using the href property of the Dynamic Content Control to perform the content switching. I know that makes the BasicLeafNodes Links. So, not sure how the Navigator records which link is being executed and how to capture that.
MJ
Add a value is the submitValue property
And in the onItemClick Event
Assign the submitted value to a viewScope variable
viewScope.Selected=context.getSubmittedValue()
And finally check if the viewScope variable equals your item submit value in the selected property. This needs to be calculated
if(viewScope.Selected="byCategory"){
return true
}else{
return false
}
The following is working for me:
if(viewScope.Selected == "byCategory"){
return true
} else{
return false
}
An equality test must be made with two equal symbols (or three). One equal symbol evidently always returns true.
I did it by jQuery. Just put the following code to the custom control, which contains navigator.
$( function() {
if (window.location.hash.length > 0) {
select()
}
});
$(window).on('hashchange', function() {
select();
});
function select() {
$(".lotusColLeft .lotusMenu .lotusBottomCorner li").removeClass(
"lotusSelected")
$(".lotusColLeft .lotusMenu .lotusBottomCorner li a")
.filter(
function() {
return window.location.hash.indexOf($(this).attr(
'href')) > -1
}).parent().addClass("lotusSelected")
}
I have 2 models. Category and Post. They are connected using a has_many_and_belongs_to_many relationship. I checked in the rails console and the relationship works.
I created checkboxes in activeadmin to set the post categories using this form field:
f.input :categories, as: :check_boxes, collection: Category.all
The problem is when I try to save it because every other field data (title, body, meta infos etc.) is saved, but the category stays the same even if I unchecked it, or checked another too.
I am using strong parameters like this:
post_params = params.require(:post).permit(:title,:body,:meta_keywords,:meta_description,:excerpt,:image,:categories)
Please give me some suggestions to make active admin save the categories too!
Best Wishes,
Matt
Try this in AA:
controller do
def permitted_params
params.permit post: [:title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: []]
end
end
Put something like this in /app/admin/post.rb:
ActiveAdmin.register Post do
permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, category_ids: [:id]
end
If you are using accepts_nested_attributes_for then it would look like this:
ActiveAdmin.register Post do
permit_params :title, :body, :meta_keywords, :meta_description, :excerpt, :image, categories_attributes: [:id]
end
I've tested, this might works for you and others as well
# This is to show you the form field section
form do |f|
f.inputs "Basic Information" do
f.input :categories, :multiple => true, as: :check_boxes, :collection => Category.all
end
f.actions
end
# This is the place to write the controller and you don't need to add any path in routes.rb
controller do
def update
post = Post.find(params[:id])
post.categories.delete_all
categories = params[:post][:category_ids]
categories.shift
categories.each do |category_id|
post.categories << Category.find(category_id.to_i)
end
redirect_to resource_path(post)
end
end
Remember to permit the attributes if you're using strong parameters as well (see zarazan answer above :D)
References taken from http://rails.hasbrains.org/questions/369
Would like to know is that possible to have filter with default value with active admin? This will be helpful for preloading the data for the admin user.
filter :country, :default=>'US'
You can do it by defining before_filter
before_filter :only => [:index] do
if params['commit'].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
UPD:
in some cases you need to set filter if params[:q] is empty or params[:scope] empty
so this might work better
before_filter :only => [:index] do
if params['commit'].blank? && params['q'].blank? && params[:scope].blank?
#country_contains or country_eq .. or depending of your filter type
params['q'] = {:country_eq => 'US'}
end
end
Adapted Fivells answer to work correctly with scopes and downloads. Feels hacky but seems to do the job. Annotated intention in comments.
before_filter only: :index do
# when arriving through top navigation
if params.keys == ["controller", "action"]
extra_params = {"q" => {"country_eq" => "US"}}
# make sure data is filtered and filters show correctly
params.merge! extra_params
# make sure downloads and scopes use the default filter
request.query_parameters.merge! extra_params
end
end
Fixing issue with "Clear Filters" button breaking, updated answer building on previous answers:
Rails now uses before_action instead of before_filter. It belongs in the controller like so:
ActiveAdmin.register User do
controller do
before_action :set_filter, only: [:index]
def set_filter
# when arriving through top navigation
if params.keys == ["controller", "action"]
extra_params = {"q" => {"country_eq" => "US"}}
# make sure data is filtered and filters show correctly
params.merge! extra_params
# make sure downloads and scopes use the default filter
request.query_parameters.merge! extra_params
end
end
params.delete("clear_filters") #removes "clear_filters" if it exists to clear it out when not needed
end
end
Note, ActiveAdmin uses ransack for queries (ex. {"q" => {"country_eq" => "US"}}), check out https://activerecord-hackery.github.io/ransack/getting-started/search-matches for more matches if you need something more complex than "_eq".
Also, previous answers leave the "Clear Filters" button broken. It doesn't clear the filters, the filters set here are simply re-applied.
To fix the "Clear Filters" button, I used this post as a guide How to keep parameters after clicking clear filters in ActiveAdmin.
#app/assets/javascripts/active_admin.js
# Making clear filter button work even on pages with default filters
$ ->
$('.clear_filters_btn').click ->
if !location.search.includes("clear_filters=true")
location.search = "clear_filters=true"
This removes all search params (ie filters) and adds "clear_filters=true" so the controller can tell the request came from the "Clear Filters" button.
before_action only: [:index] do
if params['commit'].blank?
extra_params = {"country_eq" => "US"}
params['q'] = {} if params['q'].blank?
params['q'].merge! extra_params
request.query_parameters.merge! extra_params
end
end
I have the answer for the Rails 2.X but not for Rails 3. How can I read the name of a current layout rendered inside a view.
My Rails2 question: Rails Layout name inside view
Thx.
Getting this to work in Rails 3.2 is a little more complicated than previously outlined. If your controller explicitly declares a layout, then the result of controller.send(:_layout) is a String, but otherwise it's an ActionView::Template. Try this:
module ApplicationHelper
def current_layout
layout = controller.send(:_layout)
if layout.instance_of? String
layout
else
File.basename(layout.identifier).split('.').first
end
end
end
in rails 5
This works for me:
def current_layout
layout = controller.class.send(:_layout)
if layout.nil?
default_layout
elsif layout.instance_of? String or layout.instance_of? Symbol
layout
else
File.basename(layout.identifier).split('.').first
end
end
For Rails 4:
controller.send(:_layout)
=> 'application'
For Rails 3.2:
controller.send(:_layout)
=> #<ActionView::Template:0x000000082bb788>
But controller.send(:_layout).identifier returns the fullpath:
/home/davidm/Documentos/Devel/myapp/app/views/layouts/application.haml
I think it should be in core, but for now you can make a helper method:
def current_layout
controller.send :_layout
end
it will return currently used layout name
I have used in Rails4 at view pages and got reuslt.
controller.send(:_layout)
I hope this help.
For rails 5:
controller.class.send(:_layout)
This does NOT work:
controller.send(:_layout)
You can do what I've done in my Ajax gem for Rails which is to wrap the _render_layout method:
ActionView::Base.class_eval do
def _render_layout_with_tracking(layout, locals, &block)
controller.instance_variable_set(:#_rendered_layout, layout)
_render_layout_without_tracking(layout, locals, &block)
end
alias_method_chain :_render_layout, :tracking
end
Then you can access the value that was set from your view (I'm pretty sure you have access to the controller there...) or in your controller in an after_filter, which is what I do.
I've written a custom RSpec 2 matcher which can be used to test layout rendering in Rails 3.
All the approaches in the previous answers try to guess the name via private methods, but there's no need to guess and can be easily accomplished with the public API:
class ApplicationController
layout :set_layout
attr_reader :layout_name
helper_method :layout_name
private
def set_layout
#layout_name = "application"
end
end
Override in any controller that won't use the standard layout:
class MyController < ApplicationController
private
def set_layout
#layout_name = "my_layout"
end
end
And now in your views:
<%= layout_name %>