Rectangle 27 104

$this->db->from('yourtable');
[... more active record code ...]
$query = $this->db->get();
$rowcount = $query->num_rows();

I was banging my head for hours, I couldn't recall the function's name... and it's not easy to find in official documentation either. I used print_r on object resulting from get_where method to guess the function's name! =)

activerecord - CodeIgniter Active Record - Get number of returned rows...

activerecord codeigniter
Rectangle 27 98

config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc. http://guides.rubyonrails.org/configuring.html

If you want to change Rails timezone AND have Active Record store times in this timezone, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local

Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.

Note Do not forget to restart your Rails server after modifying application.rb.

config.active_record.default_timezone
  • :local (converts to the timezone defined in config.time_zone)

Here's how you can find all available timezones

rake time:zones:all

@Mihai-AndreiDinculescu Do you think that is better to store the datetime values in UTC in the database and then just change them in the frontend like with moment.js or what do you suggest in order to show this data in the correct time zone for any user?

ruby - How to change default timezone for Active Record in Rails? - St...

ruby-on-rails ruby activerecord timezone
Rectangle 27 96

config.active_record.default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :utc. http://guides.rubyonrails.org/configuring.html

If you want to change Rails timezone AND have Active Record store times in this timezone, use

# application.rb
config.time_zone = 'Eastern Time (US & Canada)'
config.active_record.default_timezone = :local

Warning: you really should think twice, even thrice, before saving times in the database in a non-UTC format.

Note Do not forget to restart your Rails server after modifying application.rb.

config.active_record.default_timezone
  • :local (converts to the timezone defined in config.time_zone)

Here's how you can find all available timezones

rake time:zones:all

@Mihai-AndreiDinculescu Do you think that is better to store the datetime values in UTC in the database and then just change them in the frontend like with moment.js or what do you suggest in order to show this data in the correct time zone for any user?

ruby - How to change default timezone for Active Record in Rails? - St...

ruby-on-rails ruby activerecord timezone
Rectangle 27 25

An active record relation does not automatically load all records into memory.

When you call #each, all records will be loaded into memory. When you call #find_each, records will be loaded into memory in batches of the given batch size.

So when your query returns a number of records that would be too much memory for the server's available resources, then using #find_each would be a great choice.

It's basically like using ruby's lazy enumeration #to_enum#lazy with #each_slice and then #each (very convenient).

So code 1 may execute SQL multiple times(according to records size and batch size), code 2 only execute SQL once?

Users.for_each(batch_size) {|u| }
SELECT "users"."*" FROM "users" WHERE ("users"."id"  > 51)
SELECT "users"."*" FROM "users" WHERE ("users"."id"  > 51) LIMIT 50

ruby - In Rails, what's the difference between find_each and where? - ...

ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 activerecord
Rectangle 27 47

I could not get the above solution to work with Active Record 4.0.8 and Postgresql 9.3

change_column_null :users, :email, true

The reverse has a nice option to update existing records (but not set the default) when null is not allowed.

I'd recommend using change_column_default along with this if you want null to be the default column value. Otherwise it will be false or 0.

Rails Migration to make a column null => true - Stack Overflow

ruby-on-rails-3 migration
Rectangle 27 47

I could not get the above solution to work with Active Record 4.0.8 and Postgresql 9.3

change_column_null :users, :email, true

The reverse has a nice option to update existing records (but not set the default) when null is not allowed.

I'd recommend using change_column_default along with this if you want null to be the default column value. Otherwise it will be false or 0.

Rails Migration to make a column null => true - Stack Overflow

ruby-on-rails-3 migration
Rectangle 27 57

Whether you're using the active record class or not, you can access database errors using $this->db->_error_message() and $this->db->_error_number().

If you're using a mysql database, these functions are equivalent to mysql_error() and mysql_errno() respectively. You can check out these functions by looking at the source code for the database driver for the database you're using. They're located in system/database/drivers.

So, after you run a query, you can check for errors using something like:

if ($this->db->_error_message()) \\handle error

FYI - This only works if your db_debug flag in the database config file is set to FALSE. By default its set to TRUE in a new installation of CI 2.1

@emmychan: could we catch exception to handle DB error? Is it the same with your solution? Thanks

FYI - With PostgreSQL 9.4 / CI 2.1.3, I note that _error_number() often (always?) returns empty string but _error_message() has a (possibly multiline) error message text. So, how to parse error in various locales?

Thanks but how can I get the error message when db_debug flag is TRUE?

php - Codeigniter - handling errors when using active record - Stack O...

php codeigniter activerecord
Rectangle 27 36

For a new rails app, you can have it exclude active record by specifying the --skip-active-record parameter. Eg:

rails new appname --skip-active-record

I did this and ran a few diffs to find and remove the stuff in my current app that was using ActiveRecord

Remove ActiveRecord in Rails 3 - Stack Overflow

ruby-on-rails ruby-on-rails-3
Rectangle 27 36

For a new rails app, you can have it exclude active record by specifying the --skip-active-record parameter. Eg:

rails new appname --skip-active-record

I did this and ran a few diffs to find and remove the stuff in my current app that was using ActiveRecord

Remove ActiveRecord in Rails 3 - Stack Overflow

ruby-on-rails ruby-on-rails-3
Rectangle 27 132

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
        puts result.pop
end

seems unnecessary to order the data twice, I'm currently getting the count first and using it with offset

That was the other method I was thinking of, but that seems like even more work since that's 2 queries against the database instead of 1. I guess I assume that you need to iterate over the array at some point, so you could let ruby sort it at at that time. (ie. records.reverse.each do ..)

Alternately, you could not reverse the array and use Array.pop to iterate over the array rather than reversing it.. ruby-doc.org/core-1.8.7/classes/Array.html#M000280

For Rails 3, see Bongs' reply instead. This way still works, but is no longer the preferred way.

ruby on rails - How to get last N records with activerecord? - Stack O...

ruby-on-rails ruby activerecord
Rectangle 27 26

Do you mean for defining active record migrations? or do you mean Ruby data types?

Here's a link that may help for creating migrations:

ruby - Rails 3 datatypes? - Stack Overflow

ruby-on-rails ruby ruby-on-rails-3 rails-activerecord
Rectangle 27 26

Do you mean for defining active record migrations? or do you mean Ruby data types?

Here's a link that may help for creating migrations:

ruby - Rails 3 datatypes? - Stack Overflow

ruby-on-rails ruby ruby-on-rails-3 rails-activerecord
Rectangle 27 66

Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed by overwriting Base.inheritance_column). This means that an inheritance looking like this:

class Company < ActiveRecord::Base; end   
class Firm < Company; end  
class Client < Company; end   
class PriorityClient < Client; end

When you do Firm.create(:name => "37signals"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using Company.find(:first, "name = 37signals") and it will return a Firm object.

If you dont have a type column defined in your table, single-table inheritance wont be triggered. In that case, itll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

database - How to implement Active Record inheritance in Ruby on Rails...

ruby-on-rails database inheritance activerecord model
Rectangle 27 7

active record supports 'having' as a method. So you could do your query this way:

Account.joins(:users).select('accounts.id').group('accounts.id').having('count(users.id) > 1')

activerecord - rails 3 getting the count of the records that have more...

ruby-on-rails activerecord
Rectangle 27 30

CodeIgniter's ActiveRecord doesn't support UNION, so you would just write your query and use the ActiveRecord's query method.

$this->db->query('SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2');

To explain, CodeIgniter's ActiveRecord only supports SQL features that are compatible with all its supported SQL types (or implements them in its own way). The idea of ActiveRecord is to abstract the database type to be database independant and let people move from MySQL to MSSQL or whatever else without major issue. If they tried to add unison it would screw with other database types.

database independant and let people move from MySQL to MSSQL or whatever else without major issue

Name one popular RDBMS that does not support UNION? Other ORMs ( ActiveRecord semantics), such as SQLAlchemy, offer excellent support for UNIONs and JOINs (of various kinds) across all database back-ends, including SQLite. For back-ends which do not support it directly (e.g. SQLite), the ORM makes it work by doing a little bit more behind-the-scenes while still maintaining portability. In this particular case, by performing the query manually you lose all semblance of portability in addition to the more advanced features of the ActiveRecord system itself (e.g. table filtering).

This is not pure active record query. I was having same requirement. I got solution & given answer.

mysql - UNION query with codeigniter's active record pattern - Stack O...

mysql sql codeigniter activerecord union
Rectangle 27 29

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

php - CodeIgniter activerecord, retrieve last insert id? - Stack Overf...

php codeigniter
Rectangle 27 23

You can use an active record callback to assign the role after the user is created. Something like

class User < ActiveRecord::Base
  after_create :assign_default_role

  def assign_default_role
    add_role(:role)
  end
end

Note that there's also an after_save callback but it's called EVERY time the user is saved. So if you edit the user and save it would try to add the role again. That's why I'm using the after_create callback instead.

This is a Good solution too! ;)

you'd better check if a role is assigned before add_role

authorization - Rails & Rolify: Add default role on creation? - Stack ...

ruby-on-rails authorization roles
Rectangle 27 12

Straight from the CodeIgniter support forum:

$res = $this->db->query($str);

if (!$res) {
  // if query returns null
  $msg = $this->db->_error_message();
  $num = $this->db->_error_number();

  $data['msg'] = "Error(".$num.") ".$msg;
  $this->load->view('customers_edit_view',$data);
}

Note that you can also log Active Record errors by going into your CI app config file and setting the following:

$config['log_threshold'] = 1;

php - Codeigniter - handling errors when using active record - Stack O...

php codeigniter activerecord
Rectangle 27 46

Here is a decent slide show introducing MongoDB. I think some of the big differences is that most of the systems rely on Active Record or some similar database abstraction.

NoSql Crash Course/Tutorial - Stack Overflow

nosql
Rectangle 27 46

I think you will have to do this manually since the active record store does not implement the expire_after option. So within your (I assume) before filter, you should do this:

def authenticate
  if session[:logged_in]
    reset_session if session[:last_seen] < 2.minutes.ago
    session[:last_seen] = Time.now
  else
    ... authenticate
    session[:last_seen] = Time.now
  end
end

Obviously, this is not complete, but it should give you the basic idea.

It seems that the functionality IS present in rails since version 2.3. I found the relevant code here. This is AbstractStore which should serve as base class for all derived ones. So, as dadooda suggests, the following should work:

Some::Application.config.session_store :active_record_store, {
  expire_after: 24.hours,
}

No wonder I couldn't find it :) Thanks for the pointer.

One question here is how does this work...as in, say this before_filter is called when the session is initially created - i.e. when the user is first authenticated, how is session[:last_seen] ever called again? If it's an authenticate before_filter, is it not called just once - on authentication? I guess what I am trying to figure out in my head is, once the session is created and the user is logged in, how do I check session[:last_seen] so that if it exceeds X amount of minutes, it forces them to re-login, without doing it at the initial creationg of the session. Hope that makes sense

I hope I got your question: HTTP is stateless. The webserver therefore does not see any relationship between any two requests. But there are use cases which demand that relationship (for example authentication). In rails, the session hash provides that. But the controllers do have to read the session hash for every request in order to recognize previously authenticated users. So the 'authenticate'-before filter is called before every request. I hope this helps.

Given that I have written my authentication from scratch, does your answer work under the assumption that I explicitly call the before_filter on every single controller, or do I have to pass filter_resource_access on every single controller in order to force it to do that? I know that if I were using devise or some other authentication gem it would take care of this stuff for me - but given that I am writing one from scratch, that's why I am asking these questions.

@marcamillion: the reason for this is because by convention your controllers all inherit from ApplicationController (e.g. class PostsController < ApplicationController), so they inherit the before_filter declarations.

Setting session timeout in Rails 3 - Stack Overflow

ruby-on-rails ruby-on-rails-3 session activerecord