Model "update_attributes" returns false, yet model.errors.messages.inspect returns {} - ruby-on-rails-3

I am looking into a model "update_attributes" returning false, yet model.errors.messages.inspect returns {}. There is no errors, just a transaction rollback. Below is the logs:
===========>>>>>>>>>>> #user.errors.messages.inspect ======
{}
Started PUT "/authentify/users/4" for 127.0.0.1 at 2012-12-20 00:01:57 -0600
Processing by Authentify::UsersController#update as HTML
Parameters: {"utf8"=>"√", "authenticity_token"=>"Y01zI3oQmccemTJvBnHmff04w4raAcBLwdQ2k69wKjM=", "user"=>{"name"=>"Janexx", "login"=>"amine4", "update_password_checkbox"=>"[FILTERED]", "status"=>"active", "user_levels_attributes"=>{"0"=>{"sys_user_group_id"=>"admin", "manager_id"=>"admin", "id"=>"4"}}}, "commit"=>"Save", "id"=>"4"}
Authentify::User Load (0.0ms) SELECT "authentify_users".* FROM "authentify_users" WHERE "authentify_users"."id" = ? LIMIT 1 [["id", 1]]
Authentify::Session Load (0.0ms) SELECT "authentify_sessions".* FROM "authentify_sessions" LIMIT 1
CACHE (0.0ms) SELECT "authentify_sessions".* FROM "authentify_sessions" LIMIT 1
Authentify::User Load (0.0ms) SELECT "authentify_users".* FROM "authentify_users" WHERE "authentify_users"."id" = ? LIMIT 1 [["id", "4"]]
(0.0ms) begin transaction
Authentify::UserLevel Load (0.0ms) SELECT "authentify_user_levels".* FROM "authentify_user_levels" WHERE "authentify_user_levels"."user_id" = 4 AND "authentify_user_levels"."id" IN (4)
(1.0ms) UPDATE "authentify_users" SET "name" = 'Janexx', "updated_at" = '2012-12-20 06:01:57.100454' WHERE "authentify_users"."id" = 4
(3.0ms) rollback transaction
{}

Related

psql insert into if else

I want to make it so that when creating a user, the first user receives $ 1000 on the wallet, and the rest - $ 10 (user_id - pk)
I made this request
INSERT INTO users (user_id, login, balance, encrypted_password)
select 1, 'login',
case
when user_id = 1 then (login = 'login', balance= 1000, encrypted_password = 'password')
else (login = 'login', balance = 10, encrypted_password = 'password')
end as user_id
RETURNING user_id
but when I make this request, I get the error:
ERROR: ERROR: column "user_id" does not exist
LINE 4: when #user_id == 0 then (login = 'login', balance= '...
^
HINT: There is a "user_id" column in the "users" table, but it cannot be referenced from this part of the query.
SQL state: 42703
character: 103

When using SQL-Mock, Scan is returning an error [duplicate]

I'm trying to write tests for some code using Gorm using sqlmock. I figured out writing tests for my insert function but now pulling my hair out trying to get an update working.
First piece of the workflow merely queries the record from the database. I can't get it to match my SQL even though the log output shows them as being identical.
Here is the error message:
(/path/to/my/project/database.go:263)
[2020-01-08 10:29:40] Query: could not match actual sql: "SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1" with expected regexp "SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1"
I also tried using ExpectExec insert of ExpectQuery.
for _, c := range cases {
db, mock, err := sqlmock.New()
if err != nil {
t.Fatal(err)
}
DB, err := gorm.Open("sqlite3", db)
if err != nil {
t.Fatal(err)
}
DB.LogMode(true)
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`)
err = UpdateStoragePool(DB, &c.givenPool)
if !reflect.DeepEqual(c.wantedError, err) {
t.Fatalf("expecting errror %q, got %q", c.wantedError, err)
}
// if we didn't have any errors during the tx, check all expectations were met
if c.wantedError == nil {
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatalf(err.Error())
}
}
}
I've also tried:
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = '1')) ORDER BY "storage_pools"."id" ASC LIMIT 1`).WithArgs(1)
mock.ExpectExec(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`)
mock.ExpectExec(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = '1')) ORDER BY "storage_pools"."id" ASC LIMIT 1`).WithArgs(1)
Anyone have any ideas what I'm doing wrong here?
* UPDATE *
This DOES NOT work for select statements for some reason:
mock.ExpectExec(`SELECT \* FROM "storage_pools"`).
WithArgs(c.givenPool.PoolId).WillReturnResult(sqlmock.NewResult(1, 1))
[2020-01-13 10:32:21] call to Query 'SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1' with args [{Name: Ordinal:1 Value:1}], was not expected, next expectation is: ExpectedExec => expecting Exec or ExecContext which:
- matches sql: 'SELECT \* FROM "storage_pools"'
- is with arguments:
0 - 1
- should return Result having:
LastInsertId: 1
RowsAffected: 1
This DOES WORK but now I've hit a new problem where. For starters Gorm is doing 2 select statements for some reason... The first one works and finds the row, the second query does not find the same row. I'm at a loss here. About to just give up on this library. I could have written my own in the time we've spent trying to get it working.
db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
if err != nil {
t.Fatal(err)
}
DB, err := gorm.Open("postgres", db)
if err != nil {
t.Fatal(err)
}
DB.LogMode(true)
mockedRow := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "poolid"}).AddRow(1, time.Now(), time.Now(), "1")
// Mock the complete transaction
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`).
WithArgs(c.givenPool.PoolId).
WillReturnRows(mockedRow)
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND "storage_pools"."id" = ? AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC`).
WithArgs(1, c.givenPool.PoolId).
WillReturnRows(mockedRow)
Try this:
mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`))
Put your query into this function regexp.QuoteMeta().
mock.ExpectExec() function does not perform simple strings comparison. Instead it uses input string as RegExp to match the query.
Some characters in your SQL match string are reserved RegExp characters and should be escaped to match SQL.
Your string should look like this after escaping:
SELECT \* FROM "storage_pools" WHERE "storage_pools"\."deleted_at" IS NULL AND \(\(poolid \= \?\)\) ORDER BY "storage_pools"\."id" ASC LIMIT 1
Hint: You can escape your string online using https://www.regex-escape.com/preg_quote-online.php or some other site
Additional thought: Test with exact SQL match can be fragile without adding much extra value for exact SQL.
Test can give you false positive result if anyone made harmless change in it like adding extra space character. From other side, full text match does not catch DB schema changes that are not compatible with SQL.
I ended up with this setup for my projects:
Run unit tests with mock.ExpectExec() with basic substrings like INSERT INTO history. That makes tests much less fragile. At the same time we are still checking a lot in this test to verify code execution flow:
Number of SQL parameters
Values of these SQL parameters
Ensure that SQL command executed using mock.ExpectationsWereMet()
On top of that we have to run integration tests for our SQL queries. That is the only way to make sure that our SQL are correct and up to date with latest DB changes.
P.S. Avoid * in select. Be explicit with field names.
Update1:
Be careful with strings case. "SELECT" and "select" are two different strings.
Some code snippets from my current project:
// insert
sqlMock.ExpectExec("INSERT INTO eeo").
WithArgs("2018-12-31", "John Dow", "title"}).
WillReturnResult(sqlmock.NewResult(mock.EeoID, 1))
// select
rows := sqlmock.NewRows([]string{"req_id", "state"})
sqlMock.ExpectQuery("select").WithArgs(mock.CandidateID).WillReturnRows(rows)
This is a strange solution but worked for me. Probably a bug in sqlmock. Duplicate your mockedRow variable and plug them in ExpectQuery.
mockedRow := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "poolid"}).AddRow(1, time.Now(), time.Now(), "1")
mockedRow2 := sqlmock.NewRows([]string{"id", "created_at", "updated_at", "poolid"}).AddRow(1, time.Now(), time.Now(), "1")
// Mock the complete transaction
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC LIMIT 1`).
WithArgs(c.givenPool.PoolId).
WillReturnRows(mockedRow)
mock.ExpectQuery(`SELECT * FROM "storage_pools" WHERE "storage_pools"."deleted_at" IS NULL AND "storage_pools"."id" = ? AND ((poolid = ?)) ORDER BY "storage_pools"."id" ASC`).
WithArgs(1, c.givenPool.PoolId).
WillReturnRows(mockedRow2)
Alternatively you can create an array of mockedRow as follows:
mockedRow := []*sqlmock.Rows{
sqlmock.NewRows([]string{"id", "created_at", "updated_at", "poolid"}).AddRow(1, time.Now(), time.Now(), "1"),
sqlmock.NewRows([]string{"id", "created_at", "updated_at", "poolid"}).AddRow(1, time.Now(), time.Now(), "1"),
}
And use it as WillReturnRows(mockedRow[0]) and WillReturnRows(mockedRow[1])

Concurency between 2 where() clause with rails?

I have in my seed.rb something like :
c1 = Chapter.where(number: 1).first_or_create
a1 = Article.where(number: 1, text: 'foo bar' chapter: c1).first_or_create
a2 = Article.where(number: 2, text: 'foo bar baz', chapter: c1).first_or_create
and in Article class :
class Article
belongs_to :chapter
before_create do
self.foo = true if Article.where(chapter_id: chapter_id).count == 0
# I tried this version too, same problem : self.foo = true if chapter.articles.count == 0
end
end
the query excepted to count is :
SELECT COUNT(*) FROM articles WHERE `articles`.`chapter_id` = 1
BUT, SQL log, I have :
for the first article :
SELECT COUNT(*) FROM articles WHERE `articles`.`number` = 1 AND `articles`.`text` = "foo bar" AND `articles`.`chapter_id` = 1 AND (`articles`.`chapter_id` = 1)
and for the second article :
SELECT COUNT(*) FROM articles WHERE `articles`.`number` = 2 AND `articles`.`text` = "foo bar baz" AND `articles`.`chapter_id` = 1 AND (`articles`.`chapter_id` = 1)
My problem is before_createis call before create, so the where in seed.rb is alwais in cache and is combinate with the where in query to count...
So the count are alwais equals to 0, so foo property alwais set at true for all articles
How can I do an independant query?

How do I clear values from text_field_tag after browser refresh?

I'm having an issue with text_field_tag. I want to reset the value of
the text_field when I refresh my browser, seems like a very simple
thing, however I'm having hard time finding the answer.
After I input some values, how do i reset the value to nil or empty??
my code is below
<%= text_field_tag 'access_code', nil,
%>
Any help or tip will be greatly appreciated.
This is my session new page and access_code which I enter in text field is define in config.yml file.
If I don't enter any access code in text field still I get the value in my controller which I enter last time...how can I reset the value?......
Thanks in advance!
logs-
:
Started POST "/login" for 127.0.0.1 at 2015-06-09 16:14:26 +0530
I, [2015-06-09T16:14:26.368484 #6707] INFO -- : Processing by SessionsController#new as HTML
I, [2015-06-09T16:14:26.368731 #6707] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"Dw7fO0ZyO4/ZPnNknuXbt4xsLkGWlxM3rmaEYvClTDRjq0dLdVUGt84Pw2ZNBQ8Sz2x7BGZwlHCmq3EozDmoJg==", "access_code"=>"12345", "login"=>"admin", "password"=>"[FILTERED]", "commit"=>"Log in"}
D, [2015-06-09T16:14:26.372837 #6707] DEBUG -- : [1m[36mActiveRecord::SessionStore::Session Load (0.7ms)[0m [1mSELECT `sessions`.* FROM `sessions` WHERE `sessions`.`session_id` = '261e811b132a8cf574d6733a2bf5a2f4' ORDER BY `sessions`.`id` ASC LIMIT 1[0m
I, [2015-06-09T16:14:26.376843 #6707] INFO -- : checking for Mobile Device - Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.81 Safari/537.1
D, [2015-06-09T16:14:39.505665 #6707] DEBUG -- : [1m[35mSQL (1.1ms)[0m SELECT `users`.`id` AS t0_r0, `users`.`login` AS t0_r1, `users`.`email` AS t0_r2, `users`.`encrypted_password` AS t0_r3, `users`.`password_salt` AS t0_r4, `users`.`created_at` AS t0_r5, `users`.`updated_at` AS t0_r6, `users`.`remember_token` AS t0_r7, `users`.`remember_token_expires_at` AS t0_r8, `users`.`reset_password_token` AS t0_r9, `users`.`enabled` AS t0_r10, `users`.`customer_id` AS t0_r11, `users`.`status` AS t0_r12, `users`.`plain_password` AS t0_r13, `users`.`last_checked_at` AS t0_r14, `users`.`sign_in_count` AS t0_r15, `users`.`current_sign_in_at` AS t0_r16, `users`.`last_sign_in_at` AS t0_r17, `users`.`current_sign_in_ip` AS t0_r18, `users`.`last_sign_in_ip` AS t0_r19, `users`.`created_by` AS t0_r20, `users`.`failed_attempts` AS t0_r21, `users`.`disable_reason` AS t0_r22, `customers`.`id` AS t1_r0, `customers`.`name` AS t1_r1, `customers`.`customer_type` AS t1_r2, `customers`.`parent_id` AS t1_r3, `customers`.`created_at` AS t1_r4, `customers`.`updated_at` AS t1_r5, `customers`.`meta_data` AS t1_r6, `customers`.`opt_out` AS t1_r7, `customers`.`fulfilled` AS t1_r8, `customers`.`complete` AS t1_r9, `customers`.`fulfillment_issue` AS t1_r10, `customers`.`deleted_at` AS t1_r11, `customers`.`generic_bulletin` AS t1_r12, `customers`.`archived` AS t1_r13, `customers`.`vendor_rep` AS t1_r14, `customers`.`vendor_rep_email` AS t1_r15, `customers`.`vendor_rep_phone_no` AS t1_r16, `customers`.`converted_to_new_year` AS t1_r17, `customers`.`fulfillment_info` AS t1_r18, `customers`.`slug` AS t1_r19, `customers`.`start_date` AS t1_r20, `customers`.`end_date` AS t1_r21, `customers`.`bcc_on_confirmation` AS t1_r22, `customers`.`sales_tax_type` AS t1_r23, `customers`.`sales_tax_rate` AS t1_r24, `customers`.`delta` AS t1_r25, `customers`.`time_zone` AS t1_r26, `customers`.`commission_perc_req_items` AS t1_r27, `customers`.`commission_perc_optional_items` AS t1_r28, `customers`.`commission_perc_spirit_items` AS t1_r29, `customers`.`commission_perc_blended_rate` AS t1_r30, `customers`.`credit_card_processing_rate` AS t1_r31, `customers`.`monthly_service_fee` AS t1_r32, `customers`.`annual_service_fee` AS t1_r33, `customers`.`store_building_fee` AS t1_r34, `customers`.`account_setup_fee` AS t1_r35, `customers`.`fee_calculated_pre_tax` AS t1_r36, `customers`.`fee_calculated_post_tax` AS t1_r37, `customers`.`handling_fee` AS t1_r38, `customers`.`advertisement` AS t1_r39, `customers`.`payment_receiver_override` AS t1_r40, `customers`.`banner_image` AS t1_r41, `customers`.`default_payment_receiver` AS t1_r42, `customers`.`handling_fee_type` AS t1_r43, `customers`.`support_email_address` AS t1_r44, `customers`.`discount_per_order` AS t1_r45, `customers`.`discount_per_order_min_amount` AS t1_r46, `customers`.`player_number_required` AS t1_r47, `customers`.`discount_text` AS t1_r48, `customers`.`discount_max_counts` AS t1_r49, `customers`.`discount_coupon_code` AS t1_r50, `customers`.`accept_check` AS t1_r51, `customers`.`accept_credit_card` AS t1_r52, `customers`.`store_shipping_rates` AS t1_r53, `customers`.`mobile_version_enabled` AS t1_r54, `customers`.`reminder_email` AS t1_r55, `customers`.`returning_player` AS t1_r56, `customers`.`edit_order_after_closed` AS t1_r57, `customers`.`custom_text_for_receipt` AS t1_r58, `customers`.`eligibility_check_for_free_items` AS t1_r59, `customers`.`eligible_for_free_items` AS t1_r60, `customers`.`storefront_intro` AS t1_r61, `customers`.`pickup_locations` AS t1_r62, `customers`.`enable_facebook` AS t1_r63, `customers`.`allow_customer_notes_storefront` AS t1_r64, `customers`.`accept_cash` AS t1_r65, `customers`.`fb_page_id` AS t1_r66, `customers`.`league_enabled` AS t1_r67, `customers`.`status` AS t1_r68, `customers`.`agree_store_terms` AS t1_r69, `customers`.`launch_store` AS t1_r70, `customers`.`allow_shipping` AS t1_r71, `customers`.`amex_payment_method` AS t1_r72, `customers`.`copied_start_fresh_from` AS t1_r73, `customers`.`custom_message` AS t1_r74 FROM `users` LEFT OUTER JOIN `customers` ON `customers`.`id` = `users`.`customer_id` WHERE `users`.`login` = 'admin' AND `customers`.`deleted_at` IS NULL ORDER BY `users`.`id` ASC LIMIT 1
I, [2015-06-09T16:14:39.511565 #6707] INFO -- : Authentication:: Failed Login for User ID 1 Failed Login Attempts set to 2
D, [2015-06-09T16:14:39.512570 #6707] DEBUG -- : [1m[36m (0.3ms)[0m [1mBEGIN[0m
D, [2015-06-09T16:14:39.527978 #6707] DEBUG -- : [1m[35mUser Exists (0.9ms)[0m SELECT 1 AS one FROM `users` WHERE (`users`.`login` = 'admin' AND `users`.`id` != 1) LIMIT 1
D, [2015-06-09T16:14:39.534245 #6707] DEBUG -- : [1m[36mSQL (0.6ms)[0m [1mUPDATE `users` SET `failed_attempts` = 2, `updated_at` = '2015-06-09 10:44:39.514661' WHERE `users`.`id` = 1[0m
D, [2015-06-09T16:14:39.611739 #6707] DEBUG -- : [1m[35m (73.7ms)[0m COMMIT
I, [2015-06-09T16:14:39.623991 #6707] INFO -- : Rendered sessions/new.html.erb within layouts/application (5.1ms)
I, [2015-06-09T16:14:42.294270 #6707] INFO -- : Completed 200 OK in 15925ms (Views: 2680.0ms | ActiveRecord: 77.4ms)
D, [2015-06-09T16:14:42.295683 #6707] DEBUG -- : [1m[36m (0.3ms)[0m [1mBEGIN[0m
D, [2015-06-09T16:14:42.302890 #6707] DEBUG -- : [1m[35mSQL (0.5ms)[0m UPDATE `sessions` SET `data` = 'BAh7CUkiEmRvbWFpbl92ZW5kb3IGOgZFRkkiB25hBjsAVEkiEF9jc3JmX3Rv\na2VuBjsARkkiMWJLV1ljRE1uUFRnWE1iQUMwK0RVcFVNQVZVWHc1NGRIQ00z\nMVNqeWM1Qkk9BjsARkkiEnBhc3NfYXR0ZW1wdHMGOwBGaQdJIgpmbGFzaAY7\nAFR7B0kiDGRpc2NhcmQGOwBUWwZJIgplcnJvcgY7AEZJIgxmbGFzaGVzBjsA\nVHsGSSIKZXJyb3IGOwBGSUM6HkFjdGl2ZVN1cHBvcnQ6OlNhZmVCdWZmZXIi\nAaFZb3VyIHVzZXJuYW1lIG9yIHBhc3N3b3JkIGlzIGluY29ycmVjdC4gPGJy\nLz5QbGVhc2UgdHJ5IGFnYWluIG9yIGNsaWNrIHRoZSBmb2xsb3dpbmcgbGlu\nayB0byByZXNldCB5b3VyIHBhc3N3b3JkOiA8YSBocmVmPScvZm9yZ290X3Bh\nc3N3b3JkJz5Gb3Jnb3QgUGFzc3dvcmQ8L2E+Lgc7AFQ6D0BodG1sX3NhZmVU\n', `updated_at` = '2015-06-09 10:44:42.298136' WHERE `sessions`.`id` = 45
D, [2015-06-09T16:14:42.363066 #6707] DEBUG -- : [1m[36m (58.4ms)[0m [1mCOMMIT[0m
its its a js request,then you need to explicitly use jquery to make all text fields html as empty as you are using javascript to submit a form and NOT html which would have caused a total page refresh by using redirect_to: new_session_url.So in your login method,you must use something like:-
def login
##save the user info
respond_to do |format|
format.js
end
end
login.js.erb
$("#login-textbox").val(" ");
OR, YOU CAN ADD PAGE SPECIFIC JAVASCRIPT TO CLEAR TEXTBOXES ONSUBMIT
//add this js in your page
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
var isValid = true;
$('input[type="text"]').each(function() {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false)
e.preventDefault();
else
alert('Thank you for submitting');
});
});

Doing just one query search, saving it to an array and then search only the array instead of doing multiple sql queries

i have this
class PagesController < ApplicationController
def index
#textos = Texto.all
#texto_historia = Texto.where(:title => "História").first.contents
#texto_capas_para_sofa = Texto.where(:title => "Capas para Sofá").first.contents
#texto_cortinas = Texto.where(:title => "Cortinas").first.contents
#texto_almofadas = Texto.where(:title => "Almofadas").first.contents
end
The SQL output is:
←[1m←[36mTexto Load (2.0ms)←[0m ←[1mSELECT "textos".* FROM "textos"←[0m
←[1m←[35mTexto Load (1.0ms)←[0m SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Hist├│ria') LIMIT 1
←[1m←[36mTexto Load (0.0ms)←[0m ←[1mSELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Capas para Sof├í') LIMIT 1←[0m
←[1m←[35mTexto Load (1.0ms)←[0m SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Cortinas') LIMIT 1
←[1m←[36mTexto Load (1.0ms)←[0m ←[1mSELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Almofadas') LIMIT 1←[0m
←[1m←[35mTexto Load (0.0ms)←[0m SELECT "textos".* FROM "textos" WHERE ("textos"."title" = 'Informa├º├╡es de Contato') LIMIT 1
What i want is to do just one query for all "textos" model and then search inside an array or anything like that to get the specific variable.
You will need to get the array of all ActiveRecord objects and convert it into a hash storing the data you need.
#textos = Texto.all.inject({}) {|h, obj| h[obj.title] = obj.contents; h }
Then you will be able to access your contents with #textos["title"].
I think you want the find or find_all option:
#texto_historia = #texto.find { |a| a.title = "História"}