Ruby/Rails: dynamically change attribute in shared partial - ruby-on-rails

This should be a layup for someone...
I'm trying to change a form field's attribute depending on which controller/model is calling the partial containing the form fields...
The issue (below) is with parent_id... which references one of two columns in a dogs table. It needs to either be kennel_id or master_id depending on which view this partial is being rendered in.
Not comfortable enough, yet, with Ruby/Rails language/syntax/tools to dynamically change this without getting bogged down in if/else statements.
I'm calling a shared partial and passing in a local variable:
= render "dogs/form", :parent => #kennel
or
= render "dogs/form", :parent => #master
In the partial I'd like to:
= form_for ([parent, target.dogs.build]) do |f|
= render "shared/error_messages", :target => parent
.field
= f.label :name
= f.text_field :name
.field
= f.hidden_field :parent_id ### <= PROBLEM
.actions
= f.submit 'Save'

Just thinking out loud:
I don't know if the parent-models have the proper names for it, but you could do something like:
= f.hidden_field "#{parent.class.name.underscore}_id"
But that doesn't look right. So, why not pass it as an argument?
= render "dogs/form", :parent => #master, :foreign_key => :master_id
Or, create aliases on the dog model to handle some sort of dynamic delegation:
class Dog
def parent_id=(parent_id)
case parent.class
when Master then self.master_id = parent_id
when Kennel then self.kennel_id = parent_id
end
end
def parent_id
case parent.class
when Master then self.master_id
when Kennel then self.kennel_id
end
end
end
But that sucks too. Could the relation be polymorphic? Then you can leave out the switching.
class Dog
belongs_to :owner, :polymorphic => true
end
= f.hidden_field :owner_id
Just some ideas. Hopefully one of them makes sense to you...

Wow, my initial answer wasn't even close. I think what you'll want is a polymorphic association: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations This way, the parent can be whatever class you need it to be.

Related

Creating a form for a has_and_belongs_to_many relationship

I've read through a lot of posts regarding this topic, but not one actually provides a good answer.
I have a class A and a class B who are related through a has_and_belongs_to_many relationship.
class A < ApplicationRecord
has_and_belongs_to_many :bs
end
class B < ApplicationRecord
has_and_belongs_to_many :as
end
What I need is a form for class A showing a selection field with all the instances of B to select. Also, when editing and instance of A, the form should present a list of the related instances of B and a way to mark them for removal.
I have tried creating the list of existing instances by providing a hidden field with the id for each instance of B. And I have created a selection field using the select_tag. The code looked something like that:
= form_for #a do |f|
.field
= f.label :name
= f.text_field :name
.field
- #a.bs.each_with_index do |b, i|
= b.name
= hidden_field_tag "a[b_ids][#{i}]", b.id
.field
= select_tag "a[b_ids][]", options_from_collection_for_select(#bs, "id", "name")
.actions
= f.submit 'Save'
This worked just fine when creating the new instance of A. But when I tried to edit it, there seems to be a problem making the execution fall back to using POST instead of PATCH. And since with there is now route for POST when editing/updating this obviously ended in an exception.
So I wonder if there is any clean way to create the form I need?

has_one relationship without nested_form

I'm trying to implement a has_one relationship through a basic form and am getting completely stuck.
I seem to have tried huge numbers of combinations of things in controllers and forms but don't seem to be getting anywhere.
I have a phone number for which I use an external service populated by an api.
Eventually I would like to have all the phone numbers of this type set up for this, but right now I'd be happy with getting just one working.
parent.rb
has_one :clever_phone
And a phone model
clever_phone.rb
attr_accessible :number, :parent_id, :prefix, :country_iso
belongs_to :parent
Controller
clever_phones_controller
def new
#parent = Parent.find(params[:parent_id])
#clever_phone = #parent.build_clever_phone
def create
#parent = Parent.find(params[:parent_id]
#clever_phone = Parent.create_clever_phone(params[:clever_phone])
View
I really don't want to do a nested form from the parent here as I have some complicated code which generates information used in the creation through an api that sits, correctly I think, in the clever_phones_controller
#simple_form_for #clever_phone do |f|
= f.input :country_iso, as: :country, :iso_codes => true, priority: ["gb"]
= f.input :prefix
= f.submit
Routes
resources :parent do
resource :clever_phone
end
My issue is that the params for #parent don't seem to be being passed to the create method in the controller and thus I get a
'Can't find parent without ID'
error
If I try it as a nested form
I get
NoMethodError undefined method 'parent_clever_phones_path'
When in fact I've not used that, only parent_clever_phone_path (note the absence of plural).
I'm sure this should be really simple but I've stared at it for hours now and am at the end of my tether...
Any ideas?
Okay, there are several issues which you need to contend:
--
Variable
The reason why #parent params are not being passed is because you've not included them in your form. This is where nesting your forms would come in very handy - passing your parent params, and your clever_phone params in a single call
Since you don't want to do this, I would recommend at least populating a hidden field with the parent_id that the clever_phone is associated with:
#app/views/clever_phones/new.html.erb
= simple_form_for #clever_phone do |f|
= f.input :parent_id, as: :hidden, value: params[:parent_id]
= f.input :country_iso, as: :country, :iso_codes => true, priority: ["gb"]
= f.input :prefix
= f.submit
--
Route
Alternatively, you have to make sure you're able to create the correct route for your form (as I think the #parent = Parent.find params[:parent_id] is not being called on your create method:
#app/views/clever_phones/new.html.erb
= simple_form_for [#parent, #clever_phone] do |f|
This will give you the ability to point your create action to the nested version of your route; hence providing the parent_id param for you
--
Having written, this I don't think it will address the core of your issue. If you need more information, please write a comment & I'll happily work to create a more appropriate answer!
Right: Worth putting in the solution that finally worked.
Thanks to Rich Peck for getting me halfway there...
model
parent.rb
has_one :clever_phone
clever_phone.rb
belongs_to :parent
view
simple_form_for #clever_phone, url: parent_clever_phone_path(#parent) do |f|
-----
f.input :parent_id, :value: #parent.id
-----
routes
resources :parent do
resource :clever_phone
controller
def new
....
#parent = Parent.find(params[:parent_id])
#clever_phone = #parent.build_clever_phone
def create
#parent = Parent.find(params[:parent_id]
#clever_phone = CleverPhone.new(params[:clever_phone]
Unless you do build_clever_phone the parent_id won't populate. I couldn't get #parent.create_clever_phone to work, but this seemed to do the trick...
Hope that saves somebody a days work...

simple_form association field not pre-selecting selected elements

I have a Message data model in Rails with a "virtual" association. That is, a method that returns a collection of "associated objects", but it is not an actual association in the ActiveRecord sense.
class Message
def recipients
#recipients
end
def recipients=(arr)
#recipients = arr
end
end
The thing with simple_form is that, when I try to show a association field, it fails because there's no :recipients association:
= simple_form_for(#message) do |f|
= f.association :recipients, collection: Recipient.all
The solution seemed then simple, I went on to use a f.input with the as: :select option:
= simple_form_for(#message) do |f|
= f.input :recipients, as: :select, collection: Recipient.all
And this works fine, except for the fact that it does not automatically detect the values already in #message.recipients so that the elements appear pre-selected when the form is rendered.
If Message#recipients were an actual association, in the ActiveRecord sense, then f.association in the form would do this as well. But for reasons that go beyond the scope of this question, I can't make it as an actual association.
The question then is, can I achieve f.input :recipients, as: :select to pre-select the selected elements?
Well, this is embarrassing. Just after posting this, I came up with an idea that ended up solving the problem:
class Message
# ...
def recipient_ids
# ...
end
def recipient_ids=(arr)
# ...
end
end
I added the recipient_ids getter and setter, in addition to the association getter and setter that I had before.
Then I updated the form input field to refer to :recipient_ids instead of :recipients:
= simple_form_for(#message) do |f|
= f.input :recipient_ids, as: :select, collection: Recipient.all

Can't convert symbol to integer error with rails simple_form nested attributes

I've seen many similar questions, and looked at the answers, but nothing seems to be helping me and I've been working on this for a while now. The error is 'Can't convert symbol into integer'. My goal is to be able to create multiple sub_groups for each race. I'm just starting with trying to create one for the time being. Here's the relevant code...
** UPDATE **
VIEW
<%= simple_form_for(#race, :url => form_path, :method => form_method, :html => { :class =>
'form-horizontal form-compressed' }) do |f| %>
<fieldset>
<%= f.simple_fields_for :sub_groups do |g| %>
<%= g.input :name, requred: false %>
<%= g.collection_radio_buttons :discount_type,
[['dollars', '$'], ['percent', '%']], :first, :last %>
<%= g.input :discount_amount, :as => :integer, required: false %>
<% end %>
<hr/>
** RACE MODEL**
class Race < ActiveRecord::Base
has_many :sub_groups
accepts_nested_attributes_for :sub_groups
attr_accessible :sub_groups_attributes
** SUB_GROUP MODEL **
class SubGroup < ActiveRecord::Base
belongs_to :race
has_many :race_users
attr_accessible :discount_amount, :discount_type, :display_results, :name
end
PARAMS
after my code update...
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"VihBL4TDT/Lte4YBji/4fp4XvOri1UgUZ8B33wQuCko=", "race"=>
{"sub_group"=>{"name"=>"dfd", "discount_type"=>"dollars", "discount_amount"=>"2"}},
"commit"=>"Next", "wizard"=>"2", "id"=>"13-test5"}
CONTROLLER
class RacesController < ApplicationController
def new
#race = Race.new
#sub_groups = #race.sub_groups.build
#wizard_step = -1
#wizard_step_name = Race.wizard_step_name_from_id #wizard_step
#wizard_mode = true
render :layout => "race_wizard"
end
def update
#race = Race.find params[:id]
#wizard_step = params[:wizard].to_i + 1
#race.wizard_step = #wizard_step
#race.update_attributes(params[:race])
end
So I took advice from answer 1, and switched to using :sub_groups in the view. Now I have a new problem, which is the sub-group fields don't show up at all, despite the fact that I built a sub_groups thing in the #new method.
I'm really stumped on how I can make this happen. This is driving me bonkers. Any help is much appreciated. Thanks!
The way fields_for works is that if you supply a symbol it checks whether your model respond to {given_symbol}_attributes=. If it does the name of sub-fields is {given symbol}_attributes, otherwise just {given_symbol}.
What you need is to add accepts_nested_attributes_for :sub_groups to your Race model. This methods will create a default setter sub_groups_attributes=, which will make fields_for :sub_groups to generate fields with name sub_groups_attributes.
You can also write your own sub_groups_attributes= method, but you need to be sure you know what you're doing there as it might be a little tricky to debug.
Note, that fields_to :sub_groups won't display fields if there are no sub_group associated with given object - you will need to build one in your controller first.

Rails nested form with accepts_nested_attributes_for with an unfortunate model name

I have a Parent model named "Controller" (Mature app, and not my decision)
belongs_to :controller
accepts_nested_attributes_for :controller
Form:
= f.fields_for :controller do |c|
= c.hidden_field :id, :value => #controller.id
= c.text_field :slw_type
which doesn't get displayed.
= f.fields_for :literally_anything_else do |c|
= c.hidden_field :id, :value => #controller.id
= c.text_field :slw_type
if change the variable name to anything else, the form builds. I have a hunch that it's a rails specific reserved name.
Question:
What's the problem? and how can I make this work?
SOLVED:
The issue was that the parent model wasn't associated with the child model yet. My mistake for not providing all the information necessary.
This worked.
def new
#controller = Controller.find(params[:controller_id])
#inspection = Inspection.new(:controller => #controller)
Therefore my fields_for form builder also worked.
Pick some innocuous variable name. not_really_a_controller or whatever. Use that for your variable and your form. Then, in your actual controller (e.g. ActionController::Base descendent), rename the incoming param so the model doesn't know any different, like so:
before_filter :filter_params
private
def filter_params
if params[:not_really_a_controller]
params[:controller] = params.delete(:not_really_a_controller)
end
end
I've used this strategy for similar reasons in the past, though not specifically for controller. Worth a try though!

Resources