I have a form to record sports times : I need minutes, seconds and hundredths of second, i.e. 1:31.43 --- I don't need the hour.
In my form I use :
<%= f.time_select :perf_time, {:discard_hour => true, :default => {:minute => '00', :second => '00'}, :include_seconds => true} %>
This displays 2 select pull-downs, one for minutes and one for seconds.
I have added a separate field for hundredths of second (type Integer):
<%= f.number_field :perf_time_cents, :in => 0..999 %>
Now I'd like to use the method .change()in my helper to change add/change the microseconds to perf_time. Here's my code, but it does not do anything.
before_save :set_perf_time
def set_perf_time
self.perf_time.change(usec: (self.perf_time_cents * 10))
end
There is no option for milliseconds in time_select because a combobox with 1000 possible values would not be user friendly.
You could use instead a separate text field for the number of milliseconds, with the HTML5 type number:
<%= f.number_field :perf_time_millis, :in => 0..999 %>
In the controller, use both the values in the selects and the text input field to get the full time in millis:
time_in_millis = params[:perf_time_millis].to_i + 1000 * (params["perf_time(5i)"].to_i * 60 + params["perf_time(6i)"].to_i))
Related
Im trying to populate a collection with Times like 20.00, 20.10, 20.20 ... 24:00. So in intervals of 10.minutes. But how to do this smartly and take into account the Time.now?
Only times that are > Time.now should be listed.
So if its 20.30 It should not show 20.10, 20.20,20.30
Example code
= f.input :order, :collection => ["20:00","20:10","20:20"... etc ["24:00"],
:default => 2,
:label => "orders,
:hint => "Select the time you want this order to be processed"
Some of the things Ive tried so far:
:collection => [(Time.now + 10.minutes).strftime("%I:%M%p").to_s]
and
#hours=(Time.now.minus_with_coercion(Time.now.midnight)/3600/2)
Any thoughts how to cleanly code this ? Thank you
Not sure to understand your problem but this could help :
Time.parse('20:00').to_datetime.step(Time.parse('23:59'), 10.minutes).to_a.map {|date| date.strftime("%I:%M%p")}
=> ["08:00PM", "08:10PM", "08:20PM", "08:30PM", "08:40PM", "08:50PM", "09:00PM", "09:10PM", "09:20PM", "09:30PM", "09:40PM", "09:50PM", "10:00PM", "10:10PM", "10:20PM", "10:30PM", "10:40PM", "10:50PM", "11:00PM", "11:10PM", "11:20PM", "11:30PM", "11:40PM", "11:50PM"]
After that, you could call the delete_if method to remove unwanted time.
Something like that :
Time.parse('20:00').to_datetime.step(Time.parse('23:59'), 10.minutes).to_a.delete_if {|date| date < DateTime.now.to_time}.map {|date| date.strftime("%I:%M%p")}
I have a Rails app that is using the simple_form gem. I have two models that are related, trades and stocks. In the form for trades, I want users to be able to enter their stock ticker symbol in a text field. Currently, I'm using the association function which renders a select box. The problem is that I want a text field instead since I have about a thousand stocks to choose from.
Is there a way I can do this (with or without Simple Form)?
the models:
class Trade < ActiveRecord::Base
belongs_to :stock
end
class Stock < ActiveRecord::Base
has_many :trades
end
the form on trades#new
<%= simple_form_for(#trade) do |f| %>
<%= f.association :stock %>
<% end %>
You should be able to just use this syntax:
<%= f.input :stock_id, :label => 'Enter your ticker:' %>
The problem here is that the user will not know what :stock_id is, as it's a reference to one of your many Stock objects.
So you probably want to implement a simple jquery autocomplete interface that returns a list of stocks like so:
[{:ticker => 'AAPL', :name => 'Apple Inc', :id => 1}, {:ticker => 'IBM', :name => 'International Business Machines', :id => 2}, etc ]
You can then display something like this as autocomplete results:
AAPL - Apple Inc
IBM - International Business Machines
and allow the user to select the one they are looking for. Behind the scenes you capture the :id and use that as your associated :stock_id.
You will need to add a stocks_controller action that takes a string and looks up Stocks based on a partial ticker and returns a max-number of stocks like 20.
def search
ticker_query = "%#{params[:ticker]}%"
stocks = Stock.where('ticker LIKE ?', ticker_query).limit(20)
render :json => stocks
end
I am finishing up my first RoR project, and am working on a leaderboard system that shows the number of points users have accrued for correctly answering quiz questions.
I am getting all of the users that have answered at least one question correct, grouping them by user_id, and displaying them in descending order by most correct using this:
#users = Point.find(:all,
:group => 'user_id',
:order => 'correct DESC', :conditions => { :correct => "yes"})
In my view, I am using this to iterate through the results:
<% #users.each_with_index do |user, index| %>
However, I am not able to get the number of correct answers per user. I tried:
user.count
but that doesn't work. How do I get the number of items per group?
You're on the right track. Seems like you would be better off using the all command with the count condition within it as opposed to the count command. Something like this:
Point.all(:select => 'user_id, count(id) as point_count', :group => :user_id, :conditions => { :correct => 'yes' }, :order => 'point_count desc', :limit => 10)
This will return 10 limited Point objects with a user_id attribute (so you can still access the user relationship), and a point_count attribute with the number of correct points said user has obtained.
Note: you could change the limit to be however many users you wanted to display in your leaderboard. This example would return 10.
It might make more sense to have your code look like this:
#points = Point.all(:select => 'user_id, count(id) as point_count', :group => :user_id, :conditions => { :correct => 'yes' }, :order => 'point_count desc', :limit => 10)
And as I said in a comment below, you could iterate through them by doing something like this (this would assume that your User model has a name attribute):
<table>
<% #points.each do |point| %>
<tr>
<td><%= point.user.name %></td>
<td><%= point.point_count %></td>
</tr>
<% end %>
</table>
I think the problem may be that you think you're getting an Array back, but you actually get a Hash back.
Try doing:
p #users
(which is equivalent to puts #users.inspect). You'll probably see it's more so something like:
{ "1" => [UserObject, UserObject], "2" => `[UserObject] }
You can even do p #users.class and you'll see it's not an array.
When you loop with a .each_with_index on a Hash, you need to do:
#users.each_with_index do |(key, value), index|
Then you can do #users[key].count or value.count.
Figured out how to get the correct count:
#users = Point.count(:group => :user_id, :conditions => { :correct => "yes"})
The most simple way should be:
#user.points.where(:correct => "yes").count
Though this will only work if have defined your associations in the user and point model like
class User < ActiveRecord::Base
has_many :points
class Point < ActiveRecord::Base
belongs_to :user
(personally I would have used a bool flag (smallint) instead of string for the "correct" column.
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)
Is it possible to group by distance using the geokit-rails gem for ActiveRecord?
Say I have 10,000 users and I want to know how many are 1 mile, 2 miles... 100 miles from a point. How can I do that in as few queries as possible?
Doing something like this kills performance obviously:
(1..100).map { |i| User.count(:within => i, :origin => location) }
Is there someway to do:
User.count(:within => 100, :origin => location, :group => "distance / 100") # some sort of math perhaps
Any point in the right direction would be awesome! Some sort of way to chunk the records in one db call by a range.
I think the following db call will do what you ask for:
result = User.all(:select => "ROUND(distance / 100) AS distance, COUNT(*) AS user_count",
:group => "ROUND(id / 100)")
Since this will not load an actual user instance, you have to specify in the select what data you want to access. Then you can loop through the result like this:
<% result.each do |group| %>
<p>Distance: <%= group.distance %>, Number of users: <%= group.user_count %></p>
<% end %>