RoR how to populate number_field with default value - ruby-on-rails-3

I have quantity and quantity_received in a table. I want to populate quantity_received with quantity value however if I overwrite this value next time I load the form I want to display the saved value.
<%= fields_for "purchase_item[]", purchase_item do |f| %>
<td><%= f.number_field :quantity_received, :min => 1, :value => purchase_item.quantity, :size => 8 %></td>
<% end %>
Does RoR have some built-in function for that?

Seems like the easiest way would be to set it when you store the original quantity field to avoid having to set it in the form.
What's wrong with the way you're doing it now?

Related

Rails: two (or more) instances of same collection_select?

I've got a collection_select instance in a form, and I'm wondering if it's possible to have two or more instances in the same form. They'd be built from the same model, and they would save as if they were checkboxes constructed in an Article.all.each loop. To have these work
<%= f.collection_select("article_ids", Article.where(:page => 1), :id, :name) %>
<%= f.collection_select("article_ids", Article.where(:page => 2), :id, :name) %>
<%= f.collection_select("article_ids", Article.where(:page => 3), :id, :name) %>
in the form is pretty much what I'm after. It's essentially a multiple select but spread over a couple of selects. The field already accepts multiple results, but when I save the form as it is above it only records the option from the final select. Any thoughts?
Cheers!
<%= select_tag "article_ids[]",options_from_collection_for_select(Article.all.collect{|i| [i.name,i.id]),:multiple => true %>
When select multiple options in select list just give article_ids[] , it will store all ids in this array then after you write query how you would store in database.
If set the select tag is multiple true then you will select multiple options other wise you get only one selected value.
or just read below link
http://api.rubyonrails.org/?q=collection%20select
If you want to give f.select then you must give like this
<%= f.collection_select :article_id, Article.all, :id , :name %>
I just went with checkboxes to solve this, because it's truly the stuff of nightmares.
<% #articles.each do |a| %>
<%= check_box_tag("doc[article_ids][]", a.id, #doc.articles.include?(a.id), :class => "article_chooser") %> <a id="<%= a.id %>" class="name"><%= a.name %></a><br />
<% end %>

Date field not saved using rails 3.0?

I have an ActiveRecord and when i click on save all records are saved except the date.
My contorller
class UsersController < ApplicationController
def create
puts params[:user]
#user1 = User.new(params[:user])
if #user1.save
saveduser = User.where("fbid = ?",params[:user][:fbid])
unless saveduser.first.nil?
session[:user] = saveduser.first
end
puts "user saved "
redirect_to "/users/dashboard"
else
puts "error while saving user"
end
end
The view
<h3>User Details</h3>
<%= form_for(#user) do |f| %>
<table>
--some columns
<tr>
<td><%= f.label :state %></td>
<td> <%= f.text_field :state %></td>
</tr>
<tr>
<td><%= f.label :dob %></td>
<td> <%= f.text_field :dob %></td>
</tr>
<%= f.hidden_field :fbid %>
</table>
<%= f.submit %>
<% end %>
<table>
In console when create method is called in UserController . I can see
{"username"=>"xxxx.xx.94", "firstname"=>"xxxx", "lastname"=>"Raxxstogi", "emaild"=>"xx.xxx#gmail.com", "city"=>"Los Angeles", "country"=>"USA", "state"=>"CA", "dob"=>"08/13/1983", "fbid"=>"xxx"}
My DB table column is
dob | date | YES | | NULL |
Where is it going wrong?
Thanks
You are using a text_field in your form to save into a Date type field in the DB. Try instead to use the date helper methods as described here:
http://guides.rubyonrails.org/form_helpers.html#using-date-and-time-form-helpers
Ruby doesn't understand your date format. You can fix this by explicitly parsing the date with Date::strptime, perhaps in the model as a setter method:
class User < ActiveRecord::Base
def dob=(date)
date = Date.strptime(date, '%m/%d/%Y') if date.is_a?(String)
write_attribute(:dob, date)
end
end
I would, however, second jordanpg's recommendation to use the date helpers in Rails, unless you know that the format will be the same every time.
it could be the problem with your date format. You can either configure active record to accept this format or convert your date param to Date object using strftime or something like it

datepicker jquery ui and rails 3(.1)

Hi i am using the date picker jquery ui in combination with rails 3.1. The date picker looks brilliant, only the date isn't stored in the database? Only sometimes...? So that's a difficult error.
This is my .js file:
$(function() {
$("#question_deadline").datepicker({ duration: 'fast', maxDate: '+2m', minDate: 'now', showOn: "button", buttonImage: "calendar.gif", buttonImageOnly: true });
$("#question_deadline").datepicker("option", "showAnim", "drop");
$("#question_deadline").datepicker("option", "dateFormat", "DD, d MM, yy");
});
In my controller there's just plain rails script:
def create
#question = Question.new(params[:question])
if #question.save
redirect_to questions_path, :notice => "Successfully created question."
else
setup_questions
render :index
end
end
In views file _form.html.erb i use a text_field to display the date:
<div class="field">
<%= f.label :content, "Question" %><br />
<%= f.text_field :content, :placeholder => "type your question here.." %>
<%= f.text_field :deadline %><br />
</div>
Are there people who have experience with datepiacker jquery ui and rails, the ryan bates episode, didn't solve it, i think that was written in rails 2.3?
Regards,
Thijs
First, you need to show us the view where you have the datepicker element. If it's like this:
<input type="text" name="question_deadline" id="question_deadline" />
When you submit this form, the parameters you receive in your controller (in the method "create") is called question_deadline. So in that create method you should first write:
if params[:question_deadline] != ""
params[:question][:question_deadline] = params[:question_deadline]
end
#add a else if this date field is compulsory in the database
This step is important because the create method will read stuff from params[:question][:question_deadline] not from params[:question_deadline] which is returned from the view.
Thus params[:question][:question_deadline] is empty when you do #question.save
To display the date, you also need to show us the controller "show" method that should be something like:
#question = Question.find(params[:id]) #or any sql request that returns info about a question.
Then in the view you can retrieve it simply with:
<%= #question.question_deadline%>
Maybe with more code from you controller and view I can elaborate on that.
I think, Rails/Ruby is not able to parse a date in this format:
$("#question_deadline").datepicker("option", "dateFormat", "DD, d MM, yy");
// full day name, day (w/o leading zero), full month name, 4-digit year
In your controller, you might want to add a line such as
def create/update
...
#question.deadline = DateTime.strptime(params[:question][:deadline], '%A, %d %B, %Y')
# assuming my jquery-to-ruby format-mapping is adequate ;-)
if #question.save
...
end
Beware, that this code easily breaks on malformed date strings.
If you don't want to change the format to, e.g. 'yy-mm-dd' (in Ruby-land it's '%Y-%m-%d'), you may want to populate the selected date to another HTML element using the altField option and hide the actual datepicker input field via CSS:
$("#somewhere_else").datepicker(
dateFormat: "%yy-%mm-%dd",
altField: "#question_deadline",
altFormat: "DD, d MM, yy",
...
);
<%= form_for #question do |f| %>
...
<%= text_field_tag 'somewhere_else', #question.deadline %>
<%= f.hidden_field :deadline %>
...
<% end %>
That'll work, at least for me :-)
—Dominik
The other option is to update the way ActiveSupport parses dates. This is outlined in Default Date Format in Rails (Need it to be ddmmyyyy)

Any possible way to set radio_button_tag values by a database set value

I have a radio_button_tag in a form, which holds various values for a persons current availability:
Mike Donnall o Available o Out of office o Vacation
So originally you open the form, and select a value, this then sets the value in the Status table for that Person.
However, there's also functionality to re-open the form and update his present status, perhaps from Vacation to Available.
My question is, is there anyway at all that radio button :checked can be modified to accept a custom method, I have found something in a similar posting, but I want the value foe that radio button to be set to the value in the DB.
My code so far, a stab in the dark perhaps:
View:
<% #people.each do |p| %>
<% #statuses.each do |s| %>
<%= "#{p.name}" %>
<%= "#{s.status_name}" -%><%= radio_button_tag ['person', p.id], ['status',
s.id], checked?(p.id) %>
<% end %>
<% end %>
Helper:
def checked?(person)
#person = person
#status = Status.find_by_sql(['select status_id from statuses where person_id = ?, #person])
if #result
return true
end
As you can see Im a bit lost here, but I understand that the method should return the value of the checkbox that needs to be checked, but Im wondering because its a checked functionality, would it only be limited to being a true or false?
So for a persons.status.id check if its true or false.
It seems from your helper's SQL that you the following relationship setup between People and Statuses:
class Person < ActiveRecord::Base
has_one :status
end
class Status < ActiveRecord::Base
belongs_to :person
end
You can access one given person status like this:
person = Person.first
person_status = person.status
Using that knowledge, your desired view outcome becomes quite simple:
<% #people.each do |p| %>
<p><%= "#{p.name}" -%>
<% #statuses.each do |s| %>
<%= "#{s.status_name}" -%>
<%= radio_button_tag ['person', p.id],
['status', s.id],
(p.status == s) ? true : false %>
<% end %>
<% end %>
You can of course extract the logic to a helper, but that doesn't seem necessary.
On a personal note, this isn't the way I'd present the information to user, it' too heavy on information in one line. I suggest you put the person's name in a p tag, and use a ul tag for the statuses.

Group and count in Rails

I have this bit of code and I get an empty object.
#results = PollRoles.find(
:all,
:select => 'option_id, count(*) count',
:group => 'option_id',
:conditions => ["poll_id = ?", #poll.id])
Is this the correct way of writing the query? I want a collection of records that have an option id and the number of times that option id is found in the PollRoles model.
EDIT: This is how I''m iterating through the results:
<% #results.each do |result| %>
<% #option = Option.find_by_id(result.option_id) %>
<%= #option.question %> <%= result.count %>
<% end %>
What do you get with this:
PollRoles.find(:all,:conditions=>["poll_id = ?",#poll.id]).collect{|p| p.option_id}
You want to use this function to do things like this
PollRoles.count(:all, :group => 'option_id') should return a hash mapping every option_id with the number of records that matched it.