There a many-to-many:
class Employee < ActiveRecord::Base
has_many :employees_and_positions
has_many :employees_positions, through: :employees_and_positions
end
class EmployeesAndPosition < ActiveRecord::Base
belongs_to :employee
belongs_to :employees_position
end
class EmployeesPosition < ActiveRecord::Base
has_many :employees_and_positions
has_many :employees, through: :employees_and_positions
end
How to implement a choice (check_boxes) positions in the form when adding an employee?
I wrote this variant:
f.inputs 'Communications' do
f.input :employees_positions, as: :check_boxes
end
It displays a list of positions in the form, but does not save nothing to the table (employees_and_positions).
How to fix?
Suppose you have an employee, you can reference the ids of the employees_positions association by using employee.employees_position_ids. Accordingly, you can mass assign pre-existing EmployeesPosition objects using a check_box for each EmployeesPosition, but you need to use the employee_position_ids attribute"
= f.input :employee_position_ids, as: :check_boxes, collection: EmployeesPosition.all
Also, make sure you've whitelisted the employee_position_ids param in your active admin resource:
ActiveAdmin.register Employee do
permit_params employee_position_ids: []
end
http://activeadmin.info/docs/2-resource-customization.html
Related
I'm having trouble setting my permitted params in active admin. The docs say "Any form field that sends multiple values (such as a HABTM association, or an array attribute) needs to pass an empty array to permit_params". Here is my code from admin/sample.rb:
ActiveAdmin.register Sample do
permit_params :title, :description, :file_type, :audio_data, :channels, :sample_rate, :file_size,
categories: []
end
When I try this all the attributes appear in my active admin table but there is nothing for categories. I'm not really sure where I'm going wrong. I've tried category_ids and sample_categories too but still it doesn't show in the table. I've also tried adding an attribute to the array, such as categories: [:name] but still nothing.
Everything behaves as it should in the app itself and I'm able to add a category when creating a sample, for example. Any suggestions about how to solve this? Here is some relevant code.
models/sample.rb
class Sample < ApplicationRecord
...
has_many :sample_categories
has_many :categories, through: :sample_categories
end
models/category.rb
class Category < ApplicationRecord
has_many :sample_categories
has_many :samples, through: :sample_categories
end
models/sample_category.rb
class SampleCategory < ApplicationRecord
belongs_to :sample
belongs_to :category
end
controllers/samples_controller.rb
...
def sample_params
params.require(:sample).permit(:title, :description, :audio, :file_type, :file_size, :sample_rate, :channels, :tag_list, category_ids: [])
end
...
Have you tried the accepts_nested_attributes_for function in your Sample model?
class Sample < ApplicationRecord
...
has_many :sample_categories
has_many :categories, through: :sample_categories
accepts_nested_attributes_for :categories
end
Try first using test or rails console if it works.
Also please update your admin/sample.rb to allow nested attributes from categories
ActiveAdmin.register Sample do
permit_params :title, :description, :file_type, :audio_data, :channels, :sample_rate, :file_size,
categories_attributes: [:id, :name, :etc]
end
Note:
if you are using active admin, the samples_controller.rb CRUD controller declaration is not required
I have the following associations setup:
class Category < ApplicationRecord
has_many :child_categories
end
class ChildCategory < ApplicationRecord
belongs_to :category
has_many :subcategories
end
class Subcategory < ApplicationRecord
belongs_to :child_category
has_many :child_subcategories
end
class ChildSubcategory < ApplicationRecord
belongs_to :subcategory
end
An example of the above structure is: Apparel(category) - Clothing(child category) - Men(subcategory) - Tshirts(child subcategory).
I have a simple form where I create a product and I would like to associate that product with a child subcategory from a collection grouped_select input. Basically this input will be multileveled, for example: Clothing(cant select this) under that Men(cant select this) and after that Tshirts(I will be able to select this and associate a product with a child subcategory).
I'm kind of stuck on how to populate the collection grouped_select input, I can only get it to show the child categories and subcategories with the following. Any ideas how I can show the child subcategories as well?
#categories = ChildCategory.where(id: params[:category])
<%= f.input :category_id, collection: #categories.order(:name), as: :grouped_select, group_method: :subcategories, include_blank: false, include_hidden: false %>
I would like to select in simple_form <%= f.association :organisators, collection: User.all %> and <%= f.association :helpers, collection: User.all %> that source of them will be User ids stored in Participation join table with appropriate enum kind, is it a way to do it automatically with ActiveRecord relations?
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :event
enum kind: [:helper, :organisator]
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :participations
has_many :organisators, class_name: 'Participation'
has_many :helpers, class_name: 'Participation'
end
class User < ActiveRecord::Base
has_many :events
has_many :participations
end
When I try to save current version then it raise: Couldn't find Participation with 'id'=1
event_params: {"helper_ids"=>["2"], "organisator_ids"=>["1"]}
I would recommend using Single Table Inheritance over an enum. Keep the existing Participation model, and create two other models (helper and organiser) which will inherit from it.
Once you have implemented this, you can have two different object types which can be referenced through relationships while sharing one database model.
Take a look at this documentation:
http://api.rubyonrails.org/classes/ActiveRecord/Inheritance.html
source of them will be User ids stored in Participation join table
You need to pull from the Participation model, not the User model:
class Participation < ActiveRecord::Base
belongs_to :user
belongs_to :event
enum kind: [:helper, :organisator]
end
class Event < ActiveRecord::Base
belongs_to :user
has_many :participations
has_many :organisators, -> { where kind: :organisator}, class_name: 'User', through: :participations, source: :user
has_many :helpers, -> { where kind: :helper}, class_name: "User", through: :participations, source: :user
end
class User < ActiveRecord::Base
has_many :events
has_many :participations
has_many :participated_events, through: :participations
end
You've basically got a has_many :through relationship.
--
Thus, you should be able to use:
#app/views/events/update.html.erb
<%= simple_form_for #event do |f| %>
<%= f.association :organisators, collection: #event.organisators %>
<%= f.association :helpers, collection: #event.helpers %>
<%= f,submit %>
<% end %>
It would help if you gave some context on what you're trying to achieve. The above code should help, we may have to tweak it a little.
I am trying to build a form that will create a new record using Simple Form, but I am having trouble showing the correct label in the dropdown list. First, the relevant models:
class Service < ActiveRecord::Base
belongs_to :business
has_one :enrollment
has_many :clients, through: :enrollment
end
class Client < ActiveRecord::Base
belongs_to :business
has_one :enrollment
has_many :services, through: :enrollment
end
class Enrollment < ActiveRecord::Base
belongs_to :service
belongs_to :client
has_many :jobs
end
class Job < ActiveRecord::Base
belongs_to :enrollment
end
The basic idea is that a client will be enrolled in one or more services. A job represents an appointment to perform the service. When creating a new job, I need to select the enrollment that the job belongs to. From the html.erb:
<%= f.association :enrollment, label_method: :service_id, value_method: :id, prompt: 'Choose an enrolled service' %>
This sort of works, but it only shows me the service_id from the Enrollment table. What I want to see is the name of the Client (fname and lname) and the name of the Service concatenated in the dropdown list, like this: "John Doe: Window Washing". The problem is that both of those come from the parents of Enrollments. Basically I need to traverse two associations to get to the label that I want.
I thought about de-normalizing so that the Enrollment record has the data I need, but I'd rather not do that.
Any ideas?
In the Enrollment class define following method:
def name
"#{client.full_name}: #{service.name}"
end
Then you should be able to use this method in your form:
<%= f.association :enrollment, label_method: :name, value_method: :id, prompt: 'Choose an enrolled service' %>
To avoid 2*n+1 sql queries prepare enrollments collection with included clients and services.
New to Rails so go easy on me :-)
I have 2 models: User and Role:
class User < ActiveRecord::Base
has_many :roles
accepts_nested_attributes_for :roles
validates_presence_of :role_id
end
class Role < ActiveRecord::Base
belongs_to :user
end
User has a role_id for the foreign key.
All I'm trying to do is be able to select a role for the user in the users/new form. I know it's easy, but I cannot seem to figure it out...I've literally read for hours today trying to figure it out. The drop down select list appears in the view, but it always fails validation (like it shows up, but never actually associates what the user selects with the User.role_id)
Here is what I have in my form partial to show the drop down:
<%= f.collection_select :role_id, Role.all, :id, :name %>
Can anyone point me in the right direction? Maybe I have to use some sort of nested forms, but nothing I have tried seems to work and this is what I currently have. Do I have to do something in my controller?
If User has many roles, your User model must not have a field: user_id, I think, and I hope, that Users Have and Belongs to many Roles. Then you need a third model:
class User < ActiveRecord::Base
has_many :user_roles
has_many :roles, through: :user_roles
end
class Role < ActiveRecord::Base
has_many :user_roles
has_many :users, through: :user_roles
end
class UserRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
validates_presence_of :role_id, :user_id
end
In your User form you can use this to update relations (look: :role_ids in plural)
<%= f.collection_select :role_ids, Role.all, :id, :name, {}, {multiple: true} %>
And the validation is now in UserRole model.
Edit: If you are using Rails 4.x you need to permit params for a collection of role_ids.
params.require(:user).permit(:user_field1, :user_field2, ... , role_ids: [])