Using Rails Gem Active Admin with Associations - ruby-on-rails-3

I'm trying out the new Rails gem http://activeadmin.info/ and it's working great! However I can't find any documentation on how to use it across associations. For example:
class Membership < ActiveRecord::Base
belongs_to :course
belongs_to :person
class Course < ActiveRecord::Base
has_many :memberships
has_many :people, :through => :memberships
class Person < ActiveRecord::Base
has_many :memberships
has_many :courses, :through => :memberships
The membership join table includes some extra data as well (ie: attendance). I'm trying to show the membership with both the course and student name - and allow filtering / sorting on those names. As far as I have found, Active Admin doesn't work across associations. Has anyone else been successful in doing that, or found another gem that does? Thanks so much!

ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :ingredients_products
end
product.rb
class Product < ActiveRecord::Base
has_and_belongs_to_many :ingredients, :join_table => :ingredients_products
end
don't forget the migrations for the joining table (:id to false!)
class CreateProductsIngredients < ActiveRecord::Migration
def self.up
create_table :ingredients_products,:id => false do |t|
t.integer :product_id
t.integer :ingredient_id
t.timestamps
end
end
def self.down
drop_table :products_ingredients
end
end
Now define the form in you ActiveAdmin resource, override the default
ActiveAdmin.register Product do
form do |f|
f.inputs "Details" do
f.input :product_name
f.input :brand
f.input :ingredients # don't forget this one!
end
end

I've been playing with ActiveAdmin for a while now, here's how I managed to get associations to work in Indexes and Forms.
I've just guessed some of your model columns below. Also note, in the form. The 'person' section will show all the columns for editing, whereas the 'course' section will just show the specified column.
ActiveAdmin.register User do
index do
column :id
column :name
column :attendance
column :person do |membership|
membership.person.name
end
column :course do |membership|
membership.course.name
end
default_actions
end
form do |f|
f.inputs "Membership" do
f.input :name
f.input :created_at
f.input :updated_at
end
f.inputs :name => "Person", :for => :person do |person|
person.inputs
end
f.inputs :name => "Course", :for => :course do |course|
course.input :name
end
f.buttons
end
end
I haven't tested this, but you should be able to apply these ideas to your case. It's working for mine.
Update: I've just read your question again and noted that you're wanting to be able to sort on the association column. I've just checked my implementation and this indeed is not working. My answer may be useless to you but I'll leave it here anyway (might help someone else).

I've just started using this gem myself, and while I haven't gotten around to showing association information, here's how you create a form for associations:
form do |f|
f.inputs
f.has_many :associations do |association|
association.inputs
end
f.buttons
end
That will give you a basic form with scaffolding.

ingredient.rb
class Ingredient < ActiveRecord::Base
has_and_belongs_to_many :products, :join_table => :ingredients_products
end
product.rb
class Product < ActiveRecord::Base
attr_accessible ingredient_ids
has_and_belongs_to_many :ingredients, :join_table => :ingredients_products
end
migration_xxx.rb
class CreateProductsIngredients < ActiveRecord::Migration
def self.up
create_table :ingredients_products,:id => false do |t|
t.integer :product_id
t.integer :ingredient_id
t.timestamps
end
end
def self.down
drop_table :products_ingredients
end
end
products.rb
ActiveAdmin.register Product do
form do |f|
f.inputs "Details" do
f.input :product_name
f.input :brand
f.input :ingredients
end
end
...
end

Related

Rails 3 - Fields_for Nested attributes not showing on form

OK this is weird, I have basically the following classes:
class PriceProfile < ActiveRecord::Base
has_many :prices
has_many :price_profile_date_ranges
attr_accessible :name, :price_profile_date_ranges_attributes
accepts_nested_attributes_for :price_profile_date_ranges
}
class PriceProfileDateRange < ActiveRecord::Base
attr_accessible :end_date, :price_profile_id, :start_date, :prices, :prices_attributes
has_many :prices, :dependent=>:destroy
belongs_to :price_profile
accepts_nested_attributes_for :prices
}
class Price < ActiveRecord::Base
attr_accessible :price_profile_date_range_id, :price_profile_id, :product_id, :value
belongs_to :price_profile
belongs_to :price_profile_date_range
belongs_to :product
}
A price profile defines a pricing scheme for a particular product whose price changes over time. The date ranges over which a price is applied is stored in the price_profile_date_range table and finally the prices table holds all the prices. I'm using the following controller & view to create the form here for setting prices while creating a date range. Basically the form has a start and end date fields and a grid i.e it would have a list of texteboxs against all products to enter the price.
This is the view:
.row
.span9
= simple_form_for(#price_profile_date_range, :class=>'well') do |f|
.form-inputs
= f.input :start_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :end_date, :required => true, :as => :string, :input_html =>{:class=>'datepicker'}
= f.input :price_profile_id, :as=>:hidden
%table.table.table-bordered.table-condensed.table-striped
%tr
%td
- #products.each do |product|
%td
=product[:name]
%td
- f.fields_for(:prices) do |price_element|
= price_element.input :value, :class=>'span1'
= price_element.input :price_profile_id, :as=>:hidden
= price_element.input :price_profile_date_range_id, :as=>:hidden
= price_element.input :product_id, :as=>:hidden
.form-actions
= f.button :submit
This isnt exactly the final form - the problem is that the f.fields_for line doesn't seem to execute. In the controller I initialise the #price_profile_date_range object with a set of prices. If I do a raise inspect it shows all the price objects even in the view however the fields_for doesn't execute at all. I'm pretty stuck here real badly.
Try changing the - to a = - sounds silly but maybe that's the problem.

How to handle multiple nested resources in ActiveAdmin?

I'm using ActiveAdmin (0.4.0) with Rails (3.1.1).
I can't find a nice way/hack to handle multiple nested resources.
Considerer 3 models as:
class Program < ActiveRecord::Base
has_many :knowledges, :dependent => :destroy
end
class Knowledge < ActiveRecord::Base
belongs_to :program
has_many :steps, :dependent => :destroy
end
class Step < ActiveRecord::Base
belongs_to :knowledge
end
And the ActiveAdmin resources:
ActiveAdmin.register Program do
end
ActiveAdmin.register Knowledge do
belongs_to :program
end
ActiveAdmin.register Step do
belongs_to :knowledge
end
In routes.rb:
namespace :admin do
resources :programs do
resources :knowledges do
resources :steps
end
end
end
Here's the urls for the index of the programs, the knowledges and the steps :
http://localhost:3000/admin/programs
http://localhost:3000/admin/programs/1/knowledges
http://localhost:3000/admin/programs/1/knowledges/1/steps
No problem for the "Knowledge" admin but the "Step" admin don't keep the nested context.
For example, when I use filters in steps#index I'm redirected to:
http://localhost:3000/admin/knowledges/1/steps?params...
But it must have been:
http://localhost:3000/admin/programs/1/knowledges/1/steps?params...
Same problem when I create a new resource:
http://localhost:3000/admin/knowledges/1/steps/new
Instead of:
http://localhost:3000/admin/programs/1/knowledges/1/steps/new
Same problem with the breadcrumb... etc...
What I've tried so far in app/admin/steps.rb:
ActiveAdmin.register Step do
belongs_to :knowledge
config.clear_action_items!
action_item :only => :index do
link_to('Create Step', new_admin_program_knowledge_step_path(knowledge.program.id, knowledge.id))
end
index do
column :id
column :knowledge
column :title
column "Actions" do |step|
link_to("Voir", admin_program_knowledge_step_path(step.knowledge.program, step.knowledge, step), :class => "member_link show_link") +\
link_to("Editer", edit_admin_program_knowledge_step_path(step.knowledge.program, step.knowledge, step), :class => "edit_knowledge member_link edit_link", :id => "knowledge_#{dom_id(knowledge)}") +\
link_to("Supprimer", admin_program_knowledge_step_path(step.knowledge.program, step.knowledge, step), :class => "member_link delete_link", :method => :delete, :confirm => "Delete?")
end
end
filter :id
filter :title
filter :subtitle
filter :stage_type
filter :order_by
filter :created_at
filter :updated_at
form :partial => "form"
end
And in app/views/admin/steps/_form.html.erb I must use the activeadmin formbuilder:
<%= semantic_form_for(resource, :url => admin_program_knowledge_steps_path(resource.knowledge.program, resource.knowledge), :builder => ActiveAdmin::FormBuilder) do |f|
f.inputs "Step" do
f.input :knowledge, :as => :hidden
f.form_buffers.last << f.template.content_tag(:li, f.template.content_tag(:label, "Knowledge")+f.template.content_tag(:p, f.object.knowledge.title))
f.input :title
f.input :order_by
end
f.buttons
end %>
Well... I'm stuck.
How to handle this nicely? Any clues appreciated...
Well, the solution is pretty simple...
https://github.com/josevalim/inherited_resources
ActiveAdmin.register Step do
controller do
nested_belongs_to :program, :knowledge
end
end

ActiveAdmin customize view for has_many :through

I'm working on a ActiveAdmin app with this models :
User
class User < ActiveRecord::Base
# A User has many roles for interact on a project
has_many :roles, :dependent => :destroy
has_many :projects, :through => :role
end
Role
class Role < ActiveRecord::Base
belongs_to :user
belongs_to :project
end
Project
class Project < ActiveRecord::Base
# A project has many roles for interact
has_many :roles, :dependent => :destroy
has_many :users, :through => :role
accepts_nested_attributes_for :roles
end
To add users with a role on each project I make this form :
form do |f|
f.inputs "Details" do # Project's fields
f.input :title
f.input :code
end
f.has_many :roles do |app_f|
app_f.inputs do
if !app_f.object.nil?
app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
end
app_f.input :user
app_f.input :senior_author
end
end
f.buttons
end
My first question is how can I make a with user.firstname + user.lastname. Actually I have something like this :
#<User:0x007fb98a7d6568>
Second question is my Role model is a list of boolean attributes :
:senior_author
:first_author
:viewer
....
Can I make a with that ?
Another solution would be to just define to_s in the model:
def to_s
"#{email} | #{firstname} #{lastname}"
end
No need to set :label_method.
Just add :label_method => lambda:
app_f.input :user, :label_method => lambda{|u| "#{u.email} | #{u.firstname} #{u.lastname}" }
I fix it by adding this method to models/user.rb
# format label for formtastic dropdown menu
def to_label
"#{email} | #{firstname} #{lastname}"
end
And I use it like this :
app_f.input :user, :include_blank => false, :label_method => :to_label

Does accepts_nested_attributes_for work with belongs_to?

I have been getting all kinds of conflicting information regarding this basic question, and the answer is pretty crucial to my current problems. So, very simply, in Rails 3, is it allowed or not allowed to use accepts_nested_attributes_for with a belongs_to relationship?
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
In a view:
= form_for #user do |f|
f.label :name, "Name"
f.input :name
= f.fields_for :organization do |o|
o.label :city, "City"
o.input :city
f.submit "Submit"
Nested attributes appear to work fine for a belongs_to association as of Rails 4. It might have been changed in an earlier version of Rails, but I tested in 4.0.4 and it definitely works as expected.
The doc epochwolf cited states in the first line "Nested attributes allow you to save attributes on associated records through the parent." (my emphasis).
You might be interested in this other SO question which is along the same lines as this one. It describes two possible solutions: 1) moving the accepts_nested_attributes to the other side of the relationship (in this case, Organization), or 2) using the build method to build the Organization in the User before rendering the form.
I also found a gist that describes a potential solution for using accepts_nested_attributes with a belongs_to relationship if you're willing to deal with a little extra code. This uses the build method as well.
For belongs_to association in Rails 3.2, nested model needs the following two steps:
(1) Add new attr_accessible to your child-model (User model).
accepts_nested_attributes_for :organization
attr_accessible :organization_attributes
(2) Add #user.build_organization to your child-controller (User controller) in order to create column organization.
def new
#user = User.new
#user.build_organization
end
For Ruby on Rails 5.2.1
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
Just got to your controller, suppose to be "users_controller.rb":
Class UsersController < ApplicationController
def new
#user = User.new
#user.build_organization
end
end
And the view just as Nick did:
= form_for #user do |f|
f.label :name, "Name"
f.input :name
= f.fields_for :organization do |o|
o.label :city, "City"
o.input :city
f.submit "Submit"
At end we see that #user3551164 have already solved, but now (Ruby on Rails 5.2.1) we don't need the attr_accessible :organization_attributes

Show Name instead of ID in a HABTM relationship

Excuse me if I'm being too much of a beginner but none of the other related answers worker.
I want to show the category name that the links belong to instead of the id.
Here's the migration.
class CreateCategoriesLinks < ActiveRecord::Migration
def self.up
create_table :categories_links, :id => false do |t|
t.references :category
t.references :link
end
end
def self.down
drop_table :categories_links
end
end
The categories model
class Category < ActiveRecord::Base
has_and_belongs_to_many :links
end
The links model
class Link < ActiveRecord::Base
has_and_belongs_to_many :categories
end
And here's what's in the links controller under index and show
#categories = Category.find(:all, :order => 'name')
and here's what's in the index right now but, I've tried every permutation of this that I could find.
<%= link.category.name %>
If it put <%= link.category_ids %>, it'll show the ids.
Try:
<% link.categories.each do |cat| %>
<%= cat.name %><br>
<% end %>