Nested whitelisted attributes still unpermitted - ruby-on-rails

I have three models: event, event_user, event_users_day.
event accepts nested attributes event_user which accepts event_users_day as a nested attributes as well.
class Event < ActiveRecord::Base
has_many :event_users, :dependent => :destroy, :inverse_of => :event
accepts_nested_attributes_for :event_users, :allow_destroy => true
end
class EventUser < ActiveRecord::Base
belongs_to :event, :inverse_of => :event_users
has_many :event_users_days, :dependent => :delete_all
accepts_nested_attributes_for :event_users_days, :allow_destroy => true
end
class EventUsersDay < ActiveRecord::Base
belongs_to :event_users, inverse_of: :event_users_days
validates :event_users, :presence => true
end
The simple nested form is pretty straight forward:
= simple_nested_form_for :event_users do |f|
= f.fields_for :event_users_days do |day|
= day.input :event_day_id, as: :check_boxes, collection: #daygroups
= f.submit :class => "btn btn-success"
In my controller event_user and the attributes for event_users_days are whitelisted:
#event_user = EventUser.new(params.permit(:event_id), params[:event_users].permit(:id, event_users_days_attributes: [:id, :event_day_id]))
But when I save it only the EventUser is saved as the server tells me that event_users_days is not permitted:
Unpermitted parameter: event_users_days
Any ideas of what am I doing wrong?

The Unpermitted parameter error is being literal, so your form is generating a event_users_days parameter instead of the expected event_users_days_attributes parameter, which is being rightly rejected by Rails.
I haven't used nested_form in a long time, and if you're using Rails 4 then I'm not sure that's going to be the best pick (and it's not necessary), but even so I think the problem is that you're using :event_users instead of #event_users - but generally I'd recommend switching to simple_form unless you're in an old Rails (and if you are then you should specify that when asking questions on SO).

Related

How to limit an association list based on a related model

I know that I should know this, but I cannot seem to figure it out at all and I'm still new to development...
So I have four models...
Appointments
class Appointment < ActiveRecord::Base
belongs_to :user
belongs_to :profile
belongs_to :location
end
Profiles
class Profile < ActiveRecord::Base
belongs_to :user
has_many :appointments
has_many :profile_locations
has_many :locations, through: :profile_locations
accepts_nested_attributes_for :profile_locations, reject_if: :all_blank, allow_destroy: true
accepts_nested_attributes_for :locations, reject_if: :all_blank, allow_destroy: true
end
profile_locations
class ProfileLocation < ActiveRecord::Base
belongs_to :profile
belongs_to :location
belongs_to :location_type
accepts_nested_attributes_for :location
end
and locations
class Location < ActiveRecord::Base
has_many :profile_locations
has_many :profiles, through: :profile_locations
has_many :appointments
end
On the create appointments page, I already have an associated profile on the record. I also have an association field on my simple_form for locations that I want to be able to assign to the appointment based on those tied to the profile..
I was trying something like this, but cannot seem to getting working.
%td= f.association :location, :as => :collection_select, collection: Location.where( location.profile_location.profile_id: #profile.id ), label_method: :address_1, value_method: :id, include_blank: false, :input_html => {:class => "input-small"}, :label => "Select The Location"
Am I missing something here or is there an easier way to query this? Any guidance on any of this would be helpful.
If you are are using simple_form you should be creating collection_input like this:
%td= f.input :location, collection: Location.joins(:profile_location).where(profile_locations: { profile_id: #profile.id })
Thanks ksarunas.... I needed a minor tweak, but got it running!
%td= f.association :location, :as => :collection_select, collection: Location.includes(:profile_locations).where(profile_locations: { profile_id: #appointment.profile_id })
Was getting an error trying to pull in the #profile.id and had to pluralize the profile_locationS in both places.

Selecting 'has_many through' associations in Active Admin

I've seen several questions asked about this along the same vein, e.g.
Using HABTM or Has_many through with Active Admin
but I'm still struggling to get things to work (I've tried multiple ways at this point).
My models (slightly complicated by the 'technician' alias for the user model):
class AnalysisType < ActiveRecord::Base
has_many :analysis_type_technicians, :dependent => :destroy
has_many :technicians, :class_name => 'User', :through => :analysis_type_technicians
accepts_nested_attributes_for :analysis_type_technicians, allow_destroy: true
end
class User < ActiveRecord::Base
has_many :analysis_type_technicians, :foreign_key => 'technician_id', :dependent => :destroy
has_many :analysis_types, :through => :analysis_type_technicians
end
class AnalysisTypeTechnician < ActiveRecord::Base
belongs_to :analysis_type, :class_name => 'AnalysisType', :foreign_key => 'analysis_type_id'
belongs_to :technician, :class_name => 'User', :foreign_key => 'technician_id'
end
I have registered an ActiveAdmin model for the AnalysisType model and want to be able to select (already created) Technicians to associate with that AnalysisType in a dropdown/checkbox. My ActiveAdmin setup currently looks like:
ActiveAdmin.register AnalysisType do
form do |f|
f.input :analysis_type_technicians, as: :check_boxes, :collection => User.all.map{ |tech| [tech.surname, tech.id] }
f.actions
end
permit_params do
permitted = [:name, :description, :instrumentID, analysis_type_technicians_attributes: [:technician_id] ]
permitted
end
end
Whilst the form seems to display okay, the selected technician does not get attached upon submitting. In the logs I'm getting an error 'Unpermitted parameters: analysis_type_technician_ids'.
I've tried multiple ways of doing this following advice in other related SO pages but am always coming up against the same issue, i.e. unpermitted parameterd of some nature. Can anyone point out what I am doing wrong? (I'm using Rails 4 by the way)
Managing the association via has_and_belongs_to_many or has_many relations
does not require the use of accepts_nested_attributes_for. This type of form
input is managing the Technician IDs associated with the AnalysisType record.
Defining your permitted parameters and form like the following should allow
those associations to be created.
ActiveAdmin.register AnalysisType do
form do |f|
f.input :technicians, as: :check_boxes, collection: User.all.map { |tech| [tech.surname, tech.id] }
f.actions
end
permit_params :name, :description, :instrumentID, technician_ids: []
end
In the case where the creation of new Technician records is required that is
when the accepts_nested_attributes_for would be used.
Note: Updated answer to match comments.

Multiple nested form in a HABTM relation

I'm fighting with this bug for the past few hours and I can't make sense of it and my researches didn't give an answer.
It is a basic HABTM relationship. Inputs HABTM Visualizations, and I have a cross table InputsVisualizations that has some attributes of its own.
= form_for(#visualization) do |f|
= f.input :title
= f.fields_for :inputs_visualizations do |iv|
= iv.input :color
= iv.fields_for :input do |i|
= i.input :title
= f.button :submit, "Save"
class Input < ActiveRecord::Base
# Associations ------------------
has_many :inputs_visualizations, dependent: :destroy, order: "inputs_visualizations.order ASC"
has_many :visualizations, through: :inputs_visualizations
# Attributes --------------------
attr_accessible :title, :unit
end
class InputsVisualization < ActiveRecord::Base
# Associations ------------------
belongs_to :input
belongs_to :visualization
# Attributes --------------------
attr_accessible :input_id, :visualization_id, :color, :input_attributes
accepts_nested_attributes_for :input, :reject_if => lambda { |i| i[:title].blank? }, :allow_destroy => true
end
class Visualization < ActiveRecord::Base
# Associations ------------------
has_many :inputs_visualizations, dependent: :destroy, order: "inputs_visualizations.order ASC"
has_many :inputs, through: :inputs_visualizations, order: "inputs_visualizations.order ASC"
# Attributes --------------------
attr_accessible :title, :inputs_visualizations_attributes
accepts_nested_attributes_for :inputs_visualizations, :reject_if => lambda { |a| a[:input_id].blank? }, :allow_destroy => true
end
I need a form for Visualizations that let me manage both InputsVisualizations and Inputs. As you can see in my form, there are two nested fields_for.
Case 1:
I create a nested InputsVisualization with a nested Input (both are new_record). I save the form, they both are created. Cool!
Case 2:
From the same form, I update an Input (existing record). I save, nothing is updated even though the attributes are properly passed to the controller.
I read that nested_attributes don't work with belongs_to relationship, though it created it just fine. Why doesn't it update afterwards?
Thanks
The :reject_if condition on this line looks for an :input_id but that value is not included in the form. So this could prevent the update from going through.
accepts_nested_attributes_for :inputs_visualizations, :reject_if => lambda { |a| a[:input_id].blank? }, :allow_destroy => true

Storing order in a nested form of a many-to-many relation

I have a Rails 4 app, with models Challenge and ChallengeList. It's a many-to-many relationship, so I also have a join table with model ChallengeListsChallenge. I defined this last model because I want my ChallengeLists to be ordered lists, and so used it to exploit acts_as_list:
class ChallengeList < ActiveRecord::Base
has_many :challenge_lists_challenges, :dependent => :destroy
has_many :challenges, :through => :challenge_lists_challenges
accepts_nested_attributes_for :challenges
end
class ChallengeListsChallenge < ActiveRecord::Base
default_scope :order => 'position'
belongs_to :challenge
belongs_to :challenge_list
acts_as_list :scope => :challenge_list
end
This works fine.
In my HTML, I have a form that allows the user to define a new ChallengeList. It has a nested form for Challenges:
= f.fields_for :challenges do |challenge_builder|
.field
= challenge_builder.text_field :description
But I would also like the user to be able to change the position. So I thought I'd be smart, add a field for position:
= challenge_builder.text_field :position
Of course, this doesn't work, because 'position' is set on join items, not Challenge items.
Having a nested form for ChallengeListsChallenges would give me access to the position, but is not cool because:
I need a reference to my ChallengeList id (which is not insurmountable, but not pretty either)
I can only reference existing Challenge ids
So what can I do?
Like in this question:
Set up model dependencies like so:
class ChallengeList < ActiveRecord::Base
has_many :challenge_lists_challenges, :dependent => :destroy
has_many :challenges, :through => :challenge_lists_challenges
accepts_nested_attributes_for :challenge_lists
end
class ChallengeListsChallenge < ActiveRecord::Base
default_scope :order => 'position'
belongs_to :challenge
belongs_to :challenge_list
acts_as_list :scope => :challenge_list
accepts_nested_attributes_for :challenges
end
And a doubly nested form like so:
= form_for #challenge_list do |f|
= f.fields_for :challenge_lists_challenges do |links_form|
.field
= links_form.number_field :position
%br/
= links_form.fields_for :challenge do |challenge_form|
.field
= challenge_form.text_field :description
= challenge_form.text_field :id
And it should work.

Complex virtual attributes creation/update

So basically, my app contains users (model User) who have friends (unilateral access), and who also own lists.
What I'm trying to achieve here is when creating a new list, to provide it with "accessors", picked from the user's friends.
My code is heavily inspired from the following railscast on virtual attributes.
So, here comes my User and UserAccessor model (just the relevant parts) :
class User < ActiveRecord::Base
has_many :lists, :dependent => :destroy
has_many :friendships, :dependent => :destroy
has_many :friends, :through => :friendships
end
class UserAccessor < ActiveRecord::Base
belongs_to :accessor, :class_name => "User"
belongs_to :accessible_list, :class_name => "List"
end
My List model :
class List < ActiveRecord::Base
has_many :items
belongs_to :user
has_many :user_accessors, :foreign_key => "accessible_list_id", :dependent => :destroy
has_many :accessors, :class_name => "User", :through => :user_accessors
validates :title, :presence => true, :length => { :minimum => 1 }
attr_writer :authorized_users
after_save :add_accessors
def authorized_users
#authorized_users || self.accessors.map(&:username).join(' ')
end
private
def add_accessors
if #authorized_users
accessors = #authorized_users.split(' ').map do |username|
user = User.find_by_username(username)
if user
if self.user.inverse_friends.include? user
self.user_accessors.build(:accessor_id => user.id).accessor
end
end
end
end
end
end
The form used to create or update the list is the following one :
= simple_form_for [#user, #list] do |f|
= f.input :title, :label => "Titre"
= f.input :authorized_users, :label => "Authorized users", :hint => "Separated by spaces"
%p
= f.button :submit
So my problem comes from the fact that I don't know exactly how to create/update the accessors, my code self.user_accessors.build(:accessor_id => user.id).accessor definitely not working to fill it correctly.
I'm still quite a noob in rails (and ruby in general…), so I hope what I put there was relevant enough for you to help me! Thanks in advance!

Resources