Recent notes
RSS feedonChange Event
Hello,
I’m brand new to ROR and in general server side programing. I’m a iOS developer who is trying to learn ROR.
I’m trying to use collection select to implement filtering for my page. The idea is there are a bunch of posts and I want to implement record filtering for those.
The first collection box would have parameters like “Date”, “Amount”, “Category” and based on the selection of this a secondary drop down would appear and allow the user to make a selection. The records on this page would be then filtered based on both the selection.
I have been trying out many things and have googled a lot on collection but I have reached a dead end now. I’m pretty new and just started learning ROR.
You help is much appreciated here.
Thanks in advance.
Note: the code below might be wrong and as of now its not even compiling.. currently it complaints of “remote_function” not defined…
I have a page that looks like this,
<div class=“span8”>
<% if @user.spendings.any? %> <h3> Spendings (<%= @user.spendings.count %>)</h3> <%= collection_select(:category, :category, Category.all, :id, :name, {:prompt => 'Select'})%> <%= collection_select :event, :filterType, Filters.all, :id, :filterType, {}, { :onchange => remote_function( :url => {:action => "updatelevel", :controller => "Spendings", :id => 1}, :with => "'level_id='+this.value" )}
%>
<ol class="spendings"> <%= render @spendings %> </ol> <%= will_paginate @spendings %> <% end %> </div>
An Example for using it.
Call it in a before filter in your Base or Application Controller.
before_filter :authenticate_through_api_client
def authenticate_through_api_client
# this block should return true or false authenticate_or_request_with_http_token |token,other_options| Apiclient.find_by_client_key(token).present? end
end
# Sample request type: it expects a token in headers as
Authorization:Token token=“your_token_goes_here”
Authorization is the key and Token token=“” is value
Placing it within stack at certain level
where_you_want_it = 0 (begining of stack loaded first) Rails.application.config.middleware.insert_before(where_you_want_it, Module::Class)
description for described_class
Here is an example to understand described_class
If while describing the rspec, we use a Class name in the describe part, we can use described_class method to refer to that and use it as a class in the specs within that description.
Example:
describe MyClass do it "is available as described_class" do expect(described_class).to eq(MyClass) end end
So in the above example, described_class method will return MyClass as a class.
It is a part of rspec core 3.0
Reference: http://www.relishapp.com/rspec/rspec-core/docs/metadata/described-class
Update the uniqueness field when it value dependent on another existent field without uniqueness restriction.
I’m using sub-transaction to update existent records on DB. I use this approach to update the uniqueness field when it value dependent on another existent field without uniqueness restriction.
Migration for uniqueness with existent dependent data in DB
class AddUniquenessBarToFoo < ActiveRecord::Migration class Foo < ActiveRecord::Base end def change add_column :foos, :bar, :string execute "ALTER TABLE foos ADD CONSTRAINT uk_foods_bar UNIQUE (bar)" Foo.reset_column_information Foo.all.each do |f| begin #try get unique value in a new sub-transaction Foo.transaction(requires_new: true) do f.update_attributes!(:bar => "some ops. with another non-unique existent field to set this") end rescue ActiveRecord::StatementInvalid #We can't reuse a crashed transaction. New one. Foo.transaction(requires_new: true) do #Alternative unique value, if another error exist it's another #migration problem and then raise new error. f.update_attributes!(:bar => "some operation to set this-#{f.id}") end end end change_column :foos, :bar, :string, :null => false end end
Be aware about performance that is transaction per record for big DB.
Migration for uniqueness with existent data in DB
I’m using sub-transaction to update existent records on DB. I use this approach to update the uniqueness field when it value dependent on another existent field without uniqueness restriction.
Migration for uniqueness with existent dependent data in DB
class AddUniquenessBarToFoo < ActiveRecord::Migration class Foo < ActiveRecord::Base end def change add_column :foos, :bar, :string execute "ALTER TABLE foos ADD CONSTRAINT uk_foods_bar UNIQUE (bar)" Foo.reset_column_information Foo.all.each do |f| begin #try get unique value in a new sub-transaction Foo.transaction(requires_new: true) do f.update_attributes!(:bar => "some ops. with another non-unique existent field to set this") end rescue ActiveRecord::StatementInvalid #We can't reuse a crashed transaction. New one. Foo.transaction(requires_new: true) do #Alternative unique value, if another error exist it's another #migration problem and then raise new error. f.update_attributes!(:bar => "some operation to set this-#{f.id}") end end end change_column :foos, :bar, :string, :null => false end end
Be aware about performance that is transaction per record for big DB.
usage examples
For detailed usage examples of where see “Conditions” under ActiveRecord::Base.
Updated list of statuses
The list of supported statuses is now in the layout & rendering rails guide:
http://guides.rubyonrails.org/layouts_and_rendering.html#the-status-option
Return value not correct
It seems like trap returns nil if the handler was “DEFAULT”, but calling trap with nil causes a “IGNORE”
2.0.0-p247 :020 > p trap("CHLD", "DEFAULT") nil => nil 2.0.0-p247 :021 > p trap("CHLD", nil) nil => nil
So it seems that once you trap a signal, there isn’t a way to reset them back to what they were originally.
BEWARE of options[:value] in a partial
No problem with new records however,
the following line will not display the current @ecard value on EDIT but ‘contact@host.com’.
text_field :ecard, :sender, :value => 'contact@host.com'
Don’t let your views take control, but if you insist:
text_field :ecard, :sender, :value => f.object.ecard.blank? ? 'contact@host.com' : f.object.ecard
This doesn’t make sense, since when this object was created they deleted the default, which made it blank. Why would they want it back?
Test if an array is included in another
a note for anoiaque solution…
before running you need to require set
require 'set' class Array def included_in? array array.to_set.superset(self.to_set) end end [1,2,4].included_in?([1,10,2,34,4]) #=> true
Take care with time ranges
Trying this in the console:
(1.day.from_now..5.days.from_now).overlaps?(5.days.from_now..10.days.from_now)
will blow up…
It’s fine with Dates though:
(1.day.from_now.to_date..5.days.from_now.to_date).overlaps?(5.days.from_now.to_date..10.days.from_now.to_date) # => true
Use `update_all` for Updating the Same Column for Multiple Records.
http://apidock.com/rails/ActiveRecord/Relation/update_all
Client.where( country: 'Canada' ).update_all( country_code: 'CA' )
submit button with rails javascript's onclick event handler method
Code example
<%= f.submit ‘Create User’, class: ‘buttons’, :onclick => “validate_user_form_and_submit()” %>
Correction
Where you see:
HelperData.new(datetime, options, html_options).select_hour
The correct would be:
HelperDate.new(datetime, options, html_options).select_hour
Class name and class instance must be same name.
Code works fine in Rails 3.2.13.
The "instance-level equivalent" ActiveRecord::Base#increment is NOT atomic
Typically, you want to increment counters atomically, so the class method ActiveRecord::Base.increment_counter is the right choice.
Also, there is an issue with the increment example below as it does not save automatically:
item = Item.find(1) item.foo_count # => 0 item.increment(:foo_count) item.foo_count # => 1 item.reload item.foo_count # => 0 item.increment(:foo_count) item.save item.reload item.foo_count # => 1
Found out you can't set the type to number
I am sure others have tried to do this but I thought I would add a not that tells ever one. You can’t use the type field in in rails 2.3. It is always set back to type => “text”
So if you are trying to set it to type => “number” it will not work. It always goes back to text. Sorry only way around this is to use a text_field_tag and set the type in that.
<%= text_field_tag :thing, type: "number" %>
Code above is the only way to set the type. in rails 3 you can just call number_field and it will work
Erb tags
The <% -%> is not being used since Rails 3.
The example above should be changed to:
<%= form_tag('/posts') do %> <div><%= submit_tag 'Save' %></div> <% end %>
Bug - this is not working as documented
The stacking of several after_commit lines is not working. The last line overwrites the ones before.
Using an array for the :on options is also not working.
For details look here: http://github.com/rails/rails/issues/988#issuecomment-12653474
Classy guys...
:fav_bra_size - really?
You have explain well
You have explain well about fragment caching as I was in need of this information. http://autobodycarparts.com
Statistics
Thanks for the coding part it was really helpful for me, I would apply it on my project. http://www.koolchart.com
Update multiple attributes with raw sql
You can update multiple attributes with sql for each record being updated by using the following syntax:
example
Model.update_all("foo = 'bar', baz = 'bat'")
Using find_index to return first match. Profit!
This example shows how to use find_index to return a result as soon as the first occurrence of what you are looking for is found.
Code example
class Widget < Struct.new(:name, :profit); end class WidgetManager def initialize(*widgets) @widgets = widgets end def is_any_widget_profitable? @widgets.find_index { |w| w.profit > 0 } # <== usage! end end wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', 200), Widget.new('c', 300)) wm.is_any_widget_profitable? # => 1 (wm.is_any_widget_profitable?) ? 'some profit' : 'all loss' # => "some profit" wm = WidgetManager.new(Widget.new('a', -100), Widget.new('b', -200), Widget.new('c', -300)) wm.is_any_widget_profitable? # => nil (wm.is_any_widget_profitable?) ? 'some profit' : 'all loss' # => "all loss"
Anothery way
This Worked For Me
require File.expand_path('../app/models/extenstions/active_record_ext', File.dirname(__FILE__))
I did this in application.rb
Missing documentation for options hash
The deprecated function (http://apidock.com/rails/ActiveRecord/Serialization/to_json) has more useful documentation for the options hash.