Default selected value rails not working - ruby-on-rails

I'm sorry this question might seem silly to advanced but here goes
I am trying to set the Piano type in my form to select the preselected value from the database. It currently brings up the first value instead of the preselected value, this is my form entry for the Piano:
<div class="field">
<%= form.label :Type %><br>
<%= form.select(:Type, options_for_select([['Grand', 'Grand'], ['Upright', 'Upright'], ['Console', 'Console'], ['Spinet', 'Spinet']])) %>
</div>
I have tried adding :selected => Tuning.Type to the form to preselect the entry but it doesn't seem to work.
<div class="field">
<%= form.label :Type %><br>
<%= form.select(:Type, options_for_select([['Grand', 'Grand'], ['Upright', 'Upright'], ['Console', 'Console'], ['Spinet', 'Spinet'], :selected => Tuning.Type])) %>
</div>
I'm a little confused as to whether the select box entries are supposed to be entered in my model or not as this is all new to me and I need help moving forward.
My model reads something like:
class Tuning < ApplicationRecord
validates :Client, presence: true
validates :Tel, presence: true
validates :Address, presence: true
geocoded_by :Address
after_validation :geocode
end
But includes nothing in the way of select values for 'Type', what should I do to show up the preselected type? thank you for your help.

Related

collection_select without using symbol

I have a question which should not be so difficult but I didn't find something similar and I'm not a rails expert. I want to change the names into the database trough a collection_select without adding new data.
I have these two models:
class Plan < ActiveRecord::Base
belongs_to :patient
has_many :structures,dependent: :destroy
end
########
class Structure < ActiveRecord::Base
belongs_to :plan
end
I upload some files which save data in plan and structures e.g plan name,..
I now need a form for #plan to fill in the kind of diagnose and I want also to change the names of the structure with some default name I decided (since structure names from uploaded files are different between file to file but have the same meaning )
<%= form_for #plan do |f| %>
<%= javascript_include_tag "plans_DefaultstructureNames.js" %>
<p><strong>Please select the diagnose:</strong><br>
<%= f.collection_select :diagnose, ['SRS', 'SRT', 'SBRTLung', 'SBRTLiver', 'SBRTPancreas', 'SBRTProstate'], :to_s, :to_s, :include_blank => true,prompt: true%>
</p>
<div id="SrsSrtDefault">
<p>
<strong>BODY</strong>
<%= f.collection_select :plan,:structure,#plan.structure.name , :to_s, :to_s, :include_blank => true,prompt: true%>
</p>
<p>
<strong>PTV1</strong>
<%= f.collection_select :plan,:structure,#plan.structure.name , :to_s, :to_s, :include_blank => true,prompt: true%>
</p>
</div>
Imagine that #plan.structure.name contains BOD and PTV1. I want that the user changes BOD to BODY trough a collection select but I really don't have clou..
Hope it's clear..Cheers

Rails Virtual Attribute(s) Not Validating

I guess that in many ways I'm still a newbie with some of this rails stuff.
I have ActiveRecord Model for Payments.
But, it only has two things that get added to it's table and those are done once we get a positive response back from authorize.net.
In the Controller for this model I have my Cart form.
Within the Cart form I have billing information with default values pulled from #client and the credit card information. It looks a bit like this:
<%= form_for #payment, :url => { action: "checkout" } do |f| %>
...show errors ...
<%= f.fields_for #client do |ff| %>
<%= ff.label :firstname, 'First Name*' %>
<%= ff.text_field :firstname %>
...more fields ....
<%= ff.label :zip, 'Zip*' %>
<%= ff.text_field :zip %>
<% end %>
<%= f.label :cardnumber, 'Card Number*' %>
<%= f.text_field :cardnumber %>
... more cc info fields ...
<% end %>
Now in the Model I have added attr_accessor :cardnumber, and other card info fields.
I don't have any getter or setter methods for these (perhaps that is what I am missing).
However, I do have this in the Payment Model:
validates :zip, presence: true, numericality: true
validates :cardnumber, presence: true, numericality: true
Yet, so far the form will bypass this validation all together and goes direction to the checkout. Any help would be greatly appreciated! How do I get these validations to work properly?
If you want to get into the technical details, most of Rails' baked-in validators inherit from ActiveModel::EachValidator and this validator explicitly checks the attributes collection from ActiveModel via #read_attribute_for_validation. If #zip and #cardnumber have been set up with attr_accessor they are most likely not part of #attributes and thus skipped by the validator.
The simplest workaround would be to write a private method that validates zip/cardnumber and then call .validates with the name of that validation method. The pattern that was recommended by Koz would look like this...
class Payment
attr_accessor :zip
validate :assure_zip_not_blank
private
def assure_zip_not_blank
errors.add(:zip, 'cannot be blank') if zip_blank? && new_record?
end
def zip_blank?
self.zip.blank?
end
end
Separating the validation into two methods (assure_zip_not_blank and zip_blank?) may be overkill in this particular case but it's helpful when the logic becomes more complicated and/or you can reuse the logic.

Rails form validation does not work if form is initially hidden

I am having a weird issue with rails form validation. Currently the validation works fine if the form is visible when the page loads but nothing happens if the form is initially hidden and displayed upon user interaction with the page.
Model
class PushNotification < ActiveRecord::Base
belongs_to :application, foreign_key: :appId, primary_key: :appid
validates :message, :presence => true, :length => { maximum: 75 }
validates :max_message_frequency, :presence => true, :numericality => {:only_integer => true, :greater_than => 0}
validates :appId, :presence => true
end
Html Form
<div id="push-message-tab" class="tab-section">
<%= form_for(PushNotification.new,
url: messaging_messaging_cohort_create_push_path(#application, #cohort),
remote: true, validate: true,
html: {
id: :push_notification_create_form,
class: 'new_push_notification_create ' + (#cohort.new_record? ? 'default-segment' : ''),
autocomplete: "off"
}) do |f| %>
<div class="push-form-component-header">
<%= f.label :message, 'Message' %>
<span id="message-char-counter-wrapper"><b id="char-counter">75</b> characters left</span>
</div>
<div class="actions">
<%= f.submit "Save", id:'submit-push', class: 'with-spinner', data: {waiting_text: "Saving"} %>
</div>
<% end %>
</div>
If push-message-tab element is visible when the page loads the rails form validation works great but it doesn't when I specify style="display: none" and toggle the visibility option on the fly. The form will be sent without performing any sort of validation.
I am using rails 3.1 with ruby 1.9.2
Thank you for your support
You seem to be using the client_side_validations gem.
Based on their documentation (https://github.com/bcardarella/client_side_validations) and assuming you are talking about client-side validations I would recommend trying something like this in your javascript:
$('#your_form').resetClientSideValidations();
Just after you set the form as being displayed.

Client Side Validations on Nested Field Not Generate Valiadtion

I have application rails and use client_side_validations gem with Devise to validate devise registrations form
//account.rb
has_one :user
validates :username, presence: true, uniqueness: true
//user.rb
belongs_to :account
validates :email, presence: true, uniqueness: true
//new.html.erb
<%= form_for(#user, :url => registration_path(resource_name), :validate => true) do |f| %>
<%= f.fields_for :account, :validate => true do |inner_form|%>
<div class="field">
<%= inner_form.label :username, "Username" %><br />
<%= inner_form.text_field :username %>
</div>
<% end %>
<div class="field">
<%= f.label :email, "Email" %>
<%= f.email_field :email %>
</div>
<div>
<%= f.submit "Sign up" %>
</div>
<% end %>
Validations work fine with email field but for username not worked..
help me,,, thanks
UPDATE ---validate show but this is no nested form
change :account to #account
<%= f.fields_for :account, :validate => true do |inner_form|%>
to
<%= f.fields_for #account, :validate => true do |inner_form|%>
when submit i get the error
Account(#27129348) expected, got ActiveSupport::HashWithIndifferentAccess(#26695068)
when validates not worked, html code
<input id="user_account_attributes_username" name="user[account_attributes][username]" size="30" type="text" data-validate="true">
validates worked
<input id="user_account_username" name="user[account][username]" size="30" type="text" data-validate="true">
issue
user_account_attributes_username
user[account_attributes][username]
worked
user_account_username
user[account][username]
For current DavyJonesLocker/client_side_validations version (Rails 4.2) fixing nested forms is just replacing line (in rails.validations.js or .coffee placed inside validateForm function):
name = name.replace(/\[[\da-z_]+\]\[(\w+)\]$/g, "[][$1]");
With some better regexp, which will eliminate every [ids] and [new_ids] from name string. Here is one solution presented on jeroenj/client_side_validations:
name = name.replace(/\[((?:new_)?\d+|[0-9a-f]{24})\]/g, "[]");
It's nice (as long as you have sane attributes names) but probably there are some better ways to do this. If anyone is good at writing JS regexps please help to improve it. I will try as soon as I finish current project but I'm definitely not a regexp master.
IMPORTANT:
What is more in current client_side_validations version you have to comment out if(...) { } which surrounds mentioned regexp instruction. This is just quickfix, if is probably necessary at some point but I didn't find any usage for it yet.
We found this branch which solved that problem.
I just updated my Gemfile with this line:
gem 'client_side_validations', github: "jeroenj/client_side_validations", :branch => "4-0-deeply-nested-forms"
Hope that work for you

RoR Lookup example

I have a very simple problem but cannot find a nice solution. I have a lookup code in ruby (for example, Students that live in a State):
# State lookup (id, name)
class State < ActiveRecord::Base
has_many :students
end
# Class that belogs to a state
class Student< ActiveRecord::Base
belongs_to :state
end
and in the view/students/new.html.erb view, I display the states as a drop down:
<p>
<%= f.label :state %><br />
<%= f.collection_select :state, State.find(:all),
:id, :name, :prompt => "Select a State" %>
</p>
so far, so good, but when I hit save I got an error:
State(#37872860) expected, got String(#21001240)
what seems reasonable, as I'm sending a string instead of a State object to the Student.create method.
Which is the best way of handling this in RoR? I'm getting the State object in the controller by hand and replacing it in the parameters hash, but I think should be a better way.
Thanks very much.
Fernando
<%= f.collection_select :state_id, State.find(:all), :id, :name, :prompt => "Select a State" %>
:state_id not :state
State.find(:all) should really be something that happens in your controller not your view. I don't even think its possible to access a model in the view, which may be your problem. If you do something like this in your controller:
#states = State.find(:all)
Then you use the #states variable in the view:
"Select a State" %>
I hope that helps.

Resources