Simple Form non associated model checkbox - ruby-on-rails

I'm running into a couple of problems, some of which, I think I have found a resolution. I'm trying to create a checkbox which will copy already filled in information to another form.
Let me try and paint the picture. I have a HomeAddress & OfficeAddress that belong_to a User. While many people are working from home these days, these addresses can both be the same, so when creating a User, I want them to be able to check a box which will copy the address information from HomeAddress to the OfficeAddress input fields.
<%= f.simple_fields_for :home_address do |f| %>
<%= f.input :address %>
<%= f.input :city %>
<%= f.input :state %>
<%= f.input :zipcode %>
<% end %>
<%= f.simple_fields_for :office_address do |f| %>
<%= f.input :copy_home_address, as: :boolean, checked_value: true, unchecked_value: false, input_html: { checked: false id: 'copyPrimaryLocationAddress' } %>
<%= f.input :address %>
<%= f.input :city %>
<%= f.input :state %>
<%= f.input :zipcode %>
<% end %>
Couple of questions and problems I'm running into to start. Obviously adding the default value checked: false allows me to get around having to have this attribute exist on my OfficeAddress model. I am aware that I can create my own custom one which I'm fine with as well: app/inputs/fake_checkbox_input.rb(unsure how to get it to work):
class FakeCheckboxInput < SimpleForm::Inputs::StringInput
# This method only create a basic input without reading any value from object
def input(wrapper_options = nil)
merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
tag_name = "#{#builder.object_name}[#{attribute_name}]"
template.check_box_tag(tag_name, options['value'] || 1, options['checked'], options)
end
end
This seems to get by the errors and association to a model that a form field has to have. However, the value ALWAYS stays the same. I'm trying to get it so that the value will change depending on when/if the checkbox is checked. Not to mention how to copy the information from the HomeAddress to the OfficeAddress which is a separate issue I dont know how to resolve.
Any tips on how to resolve or where to start would be helpful. I'm reading through the SimpleForm documentation but it just isn't making sense for my given circumstance.

Related

Display Errors For Nested Form

I have a nested form in my view;
<%= simple_form_for #form, url: url do |f| %>
<%= f.input :name %>
<%= f.input :description, as: :text %>
<%= f.fields_for :account, { :class => 'field' } do |ff| %>
<%= ff.collection_radio_buttons(:account_type_id, AccountType.all, :id, :name, selected: ff.object.account_type_id) { |b| radio_button_builder(b) } %>
<% end %>
Here is my Form object (extending Reform);
class ProgrammeForm < ApplicationForm
properties :name, :description, validates: {presence: true}
property :account do
property :account_type_id
validates :account_type_id, presence: true
end
end
If I submit the form without filling in any fields, then my <% if #form.errors.any? %> partial will print out three errors;
3 Errors prohibited this from being saved:
Name can't be blank
Description can't be blank
Account account type can't be blank
But there is no "error-looking" HTML on my nested form (the account_type stuff). Name and description are fine (as those are fairly straight forward). But;
fields_for doesn't put a div wrapper around the radio buttons collection to begin with.
There is no other indication that there was an error on this field (like with name and description).
How can I address these two points?

Titlecase all entries into a form_for text field

Trying to title-case all the entries from a form_for field so they're consistent going into the database for searches.
Here is my search field (file created as a partial):
<%= form_for #airport do |f| %>
Input city
<%= f.text_field :city, :value => f.object.city.titlecase %>
Input country
<%= f.text_field :country, :value => f.object.country.titlecase %>
<%= f.submit %>
<% end %>
But when I run it I get a NoMethodError:
undefined method 'titlecase' for nil:NilClass
I took instruction on the .object.city.titlecase from this post.
Can anyone help?
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base
before_save do |place|
place.city = place.city.downcase.titleize
place.country = place.country.downcase.titleize
end
end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

Rails: form_for with field for Hash

i've got model with:
class Product < ActiveRecord::Base
attr_accessible :category, :description, :img_url, :name, :price, :quantity, :tags
serialize :tags, Hash
end
and try to make form for it
<%= form_for #product do |f| %>
<%= f.label :"tags[:condition]_new", "new" %>
<%= f.radio_button :"tags[:condition]", "New", checked: true %>
<%= f.radio_button :"tags[:condition]", "Used" %>
<% end %>
unfortunately it rails raise
undefined method `tags[:condition]' for #Product:0x007fd26d965810>
<%= f.radio_button :"tags[:condition]", "Used" %> <-- ONLY FOR 2ND LINE. first is okey. WHY?!
and I can't figure out why its trying to put method on it. Has anyone idea how to make proper field for hash value?
+ Why it fails only on 2nd f.radio_button and i passes first one?
This is because you are not setting any value for 2nd radio button, try this and it will work fine.
<%= f.radio_button :"tags[:condition]", "Used", checked: false %>
As if you will not pass any value, then FormHelper class will call 'name[:condition]' method on #product to get its corresponding value, though there is no method defined in the model it raises exception.

Ruby on Rails: Passing the selected value of a drop down menu to a function

I'm using devise and I'm trying to pass the selected value of a drop down menu to a function, but it is not working. The data is being stored in a model called user.
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<%= f.select :role, options_for_select([["Job Seeker", "candidate"], ["Employer", "employer"], ["Recruiter", "recruiter"]]) %>
<% if params[:role] == "candidate" %>
<div><%= f.label :travel %><br />
<%= f.text_field :travel %></div>
<% end
if params[:role] == "employer" || params[:role] == "recruiter"
%>
<div><%= f.label :company %><br />
<%= f.text_field :company %></div>
<% end %>
<% end %>
It looks to me as though your conditionals should use the resource object, e.g. <% if resource.role == "employer" %>
You might want to pass the current value for resource.role as an argument for options_for_select
options_for_select([["Job Seeker", "candidate"], ["Employer", "employer"], ["Recruiter", "recruiter"]], resource.role)
It seems to me that you want the user to select a role, then display different fields depending on the selected role. Correct me if I'm wrong. From the portion of code which you posted it's impossible to tell exactly what your approach is. There are several ways to solve the problem including:
Post the form with the selected role and re-render the form. The process would be similar to re-rendering forms when there is e.g. a validation error.
Break up the form into multiple stages
Use javascript to detect when the value of the select has changed and then update the form by showing and hiding fields.

Ruby on Rails: Multiple Input Fields in The Same Form - Change ID/Value

Have a page where there are multiple input fields of the same thing, Posts. Right now, when a user enters in a question for, let's say 3 fields, the only one that saves to the database is the last one. Whereas, it should save all three and give them each it's own post_id. Also; if the user doesn't enter anything in for the other fields, it should not save in the database either.
new_step_4_html.erb
<%= form_for(#post) do |f| %>
<%= f.text_field :content %>
<%= f.text_field :content %>
<%= f.text_field :content %>
<% end %>
projects_controller.rb
def new_step_4
#post = Post.new
end
Right now, all it does is submit one :content field, obviously because they all share the same id/value. Unfortunately, the Railscasts #197 applies for nested forms, so the javascript and helper stuff he does all applies for nested. I would think this is something simple. Person from IRC mentioned I could do some sort of '3.times' code into the view file or something?
First of all you will probably have to edit the model of you post.
post.rb
has_many :contents, :dependent => :destroy
accepts_nested_attributes_for :contents
You will need another model to store the content fields.
so first generate a model
rails g model content post_id:integer body:text
the model
content.rb
belongs_to :post
Now, in stead of doing <%= f.text_field :content %> a few times, let rails create them, because now you basically let them overwrite each other.
3.times do
content = #post.content.build
end
the form view will be something like this:
<%= form_for #post do |f| %>
<%= f.fields_for :contents do |builder| %>
<%= builder.label :body, "Question" %><br />
<%= builder.text_area :body, :rows => 3 %><br />
<%= end %>
<p><%= f.submit "Submit" %></p>
<% end %>
I did not test this code, but the idea should be correct. Let me know if you need more info.

Resources