Foreign Key Mismatched in rails 7.0.4 - ruby-on-rails-7

I'm quite new to rails and have been studying this database migration.
I have created three tables(models) for my practices namely: **clinicstaffs, beds, **and medicalrecords,
I have edited the clinicstaffs primary key to schoolID,
class CreateClinicstaffs < ActiveRecord::Migration[7.0]
def change
create_table :clinicstaffs, id: false do |t|
t.integer :schoolID, null: false, primary_key: true
t.string :type
t.string :firstname
t.string :middlename
t.string :lastname
t.timestamps
end
end
end
and wanted to assign schoolID as a foreign key on the beds table. I used the rails g migration Add_clinicstaffs_To_beds clinicstaffs:references and produced :
class AddClinicstaffsToBeds < ActiveRecord::Migration[7.0]
def change
add_reference :beds, :clinicstaffs, null: false, foreign_key: true
end
end
but after running rake db:migrate it gives me : foreign key mismatch error.
PS C:\Users\ArmbelBernal\Desktop\MedicalRecords> rake db:migrate
== 20221202165814 AddClinicstaffsToBeds: migrating ============================
-- add_reference(:beds, :clinicstaffs, {:null=>false, :foreign_key=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:
SQLite3::SQLException: foreign key mismatch - "beds" referencing "clinicstaffs"
C:/Users/ArmbelBernal/Desktop/MedicalRecords/db/migrate/20221202165814_add_clinicstaffs_to_beds.rb:3:in `change'
Caused by:
ActiveRecord::StatementInvalid: SQLite3::SQLException: foreign key mismatch - "beds" referencing "clinicstaffs"
C:/Users/ArmbelBernal/Desktop/MedicalRecords/db/migrate/20221202165814_add_clinicstaffs_to_beds.rb:3:in `change'
Caused by:
SQLite3::SQLException: foreign key mismatch - "beds" referencing "clinicstaffs"
C:/Users/ArmbelBernal/Desktop/MedicalRecords/db/migrate/20221202165814_add_clinicstaffs_to_beds.rb:3:in `change'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
is there anyway to fix this? thanks!
=========================================================
Tried to generate a new scaffold secondbeds status:string assessment:string with a clinicstaffs:references
produces:
class CreateSecondbeds < ActiveRecord::Migration[7.0]
def change
create_table :secondbeds do |t|
t.string :status
t.string :assessment
t.references :clinicstaff, null: false, foreign_key: true
t.timestamps
end
and edited this file to:
class CreateSecondbeds < ActiveRecord::Migration[7.0]
def change
create_table :secondbeds do |t|
t.string :status
t.string :assessment
t.references :clinicstaff_schoolID, references: :clinicstaffs, null: false
t.timestamps
end
rename_column :secondbeds, :clinicstaff_schoolID_id, :clinicstaff_schoolID
add_foreign_key :secondbeds, :clinicstaffs, column: 'clinicstaff_schoolID', primary_key: 'schoolID'
end
end
this does not give me error in running rake db:migrate << how can I implement this in a model I have already created? thanks

Related

Problems running rails db:migrate with rolify

Currently trying to install rolify to my rails application
Followed the steps on github and am getting the following error after running rails db:migrate
/home/alex/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/rolify-5.2.0/lib/rolify.rb:30: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
/home/alex/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-6.0.3/lib/active_record/associations.rb:1826: warning: The called method `has_and_belongs_to_many' is defined here
rake aborted!
NoMethodError: undefined method `Migration' for ActiveRecord:Module
/mnt/d/linux-docs/projects/code/rails/kream/kream/src/db/migrate/20200511073629_rolify_create_roles.rb:1:in `<main>'
Caused by:
NoMethodError: undefined method `Migration' for ActiveRecord:Module
/mnt/d/linux-docs/projects/code/rails/kream/kream/src/db/migrate/20200511073629_rolify_create_roles.rb:1:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)
Within the migration file ammend the version number like so
class RolifyCreateRoles < ActiveRecord::Migration[6.0]
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end
create_table(:users_roles, :id => false) do |t|
t.references :user
t.references :role
end
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])
end
end

Rails 5.1 form_with triple nested form child (grandchild??) of child not inheriting attribute and not saving

My application (based on the Hartl Rails 5 tutorial) has a User model that has_many Rooms, and the Room model in turn has_many Students. I have a form for the User to create a Room (with :number attribute) with Students (with :name attribute). Though the User creation form is separate from the Room creation form, I have used the associations code from this example: https://medium.com/#mindovermiles262/triple-nested-forms-in-rails-dedbcccb5799.
When I submit the form it returns the error "Students room can't be blank". Somewhere the association between Room and Student is being lost. Below is a screenshot of the submitted form with error message:
Here is the relevant user.rb code:
class User < ApplicationRecord
has_many :rooms, dependent: :destroy
has_many :students, through: :rooms
accepts_nested_attributes_for :rooms, allow_destroy: true
accepts_nested_attributes_for :students, allow_destroy: true
...
end
users_controller.rb
private
def user_params
params.require(:user).permit(:name, :email, :school, :password,
:password_confirmation,
:rooms_attributes => [:id, :number,
:students_attributes => [:id, :name]
] )
end
room.rb:
class Room < ApplicationRecord
belongs_to :user, optional: true
has_many :students, dependent: :destroy, inverse_of:
:room
accepts_nested_attributes_for :students, allow_destroy: true
default_scope -> { order(number: :asc) }
validates :number, presence: true
validates :user_id, presence: true
end
rooms_controller.rb
class RoomsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy, :edit, :update, :show]
before_action :correct_user, only: [:show]
def new
#room = current_user.rooms.build if logged_in?
#student = #room.students.build
end
def create
#room = current_user.rooms.build(room_params)
if #room.save && #student.save
flash[:success] = "New class created."
redirect_to current_user
else
render 'rooms/new'
end
end
def destroy
end
def edit
end
def update
#room = Room.find(params[:id])
if #room.update_attribute(room_params)
redirect_to #room
flash[:success] = "Class updated."
end
end
def show
#user = User.find(params[:id])
#rooms = #user.rooms
# #number = #rooms.number
end
private
def room_params
params.require(:room).permit(:number, :students_attributes => [:id, :name])
end
end
the current_user method from sessions_helper.rb:
def current_user
if (user_id = session[:user_id])
#current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
#current_user = user
end
end
end
student.rb:
class Student < ApplicationRecord
belongs_to :room, optional: true, inverse_of: :students
validates :name, presence: true, length: { maximum: 50 }
validates :room_id, presence: true
end
students_controller.rb
class StudentsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy, :edit, :update, :show]
before_action :correct_user, only: [:show]
def new
#room = current_user.rooms.build if logged_in?
#student = #room.students.build
end
def create
if #student.save
flash[:success] = "New student created."
redirect_to current_user
else
render 'students/new'
end
end
def show
end
private
def student_params
params.require(:student).permit(:name)
end
end
the Room creation form, rooms\new.html.erb:
<% provide(:title, 'Create a class') %>
<h1>Create a class</h1>
<%= form_with(model: #room, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :number, "Class number" %>
<%= f.number_field :number, class: 'form-control' %>
<%= f.fields_for :students do |s| %>
<%= s.label :name, "Student name" %>
<%= s.text_field :name, class: 'form-control' %>
<% end %>
<%= f.submit "Create class", class: "btn btn-primary" %>
<%= params.inspect %>
<% end %>
config\routes.rb:
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
root 'static_pages#home'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/showall', to: 'users#index'
get '/createroom', to: 'rooms#new'
post '/createroom', to: 'rooms#create'
get 'createstudent', to: 'students#new'
get 'createstudent', to: 'students#create'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :rooms
resources :students
end
and development.log:
Processing by RoomsController#new as
Rendering rooms/new.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (1.0ms)
Rendered rooms/new.html.erb within layouts/application (388.0ms)
Rendered layouts/_rails_default.html.erb (244.0ms)
Rendered layouts/_shim.html.erb (1.0ms)
Rendered layouts/_header.html.erb (1.0ms)
Rendered layouts/_footer.html.erb (1.0ms)
Completed 200 OK in 2938ms (Views: 2513.1ms | ActiveRecord: 12.0ms)
Processing by RoomsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"henh7dclciYRcZE6xRFfdSHBPQuRmO03eXXEsmRkSSI25uqkMSo6WFwthixdEzDNSNjY5pPmcIYwi5nmFZirMg==", "room"=>{"number"=>"200", "students_attributes"=>{"0"=>{"name"=>"Roo"}}}, "commit"=>"Create class"}
Rendering rooms/new.html.erb within layouts/application
Rendered shared/_error_messages.html.erb (1.0ms)
Rendered rooms/new.html.erb within layouts/application (35.0ms)
Rendered layouts/_rails_default.html.erb (237.0ms)
Rendered layouts/_shim.html.erb (0.0ms)
Rendered layouts/_header.html.erb (1.0ms)
Rendered layouts/_footer.html.erb (1.0ms)
Completed 200 OK in 3283ms (Views: 494.7ms | ActiveRecord: 3.0ms)
I added :inverse_of per Rails 5 error message: Child-Model Parent-Model must exist but that made no difference. This (rails 5.1: nested form validation) does not appear relevant, b/c it involves a parent with two different children, not a parent with a child that also has a child.
Thanks in advance for any assistance.
EDIT:
I finally realized that the error message "Students room can't be blank" referred to the room_id being blank. I removed the following line from student.rb:
validates :room_id, presence: true
I had thought that
belongs_to :room, optional: true
would temporarily bypass the validates method, but I was wrong.
Removing
validates :room_id, optional: true
was the solution.

bookshelf.js transaction not working with attach

Appreciate any help that you can provide.
I'm trying to create a 'Runway' model then attach 'Model' IDs for a many-to-many relationship within a transaction.
The model is still created when an error is thrown during attach (i.e. the transaction is not rolled back). What am I doing wrong?
export function create(object) {
var data = _.pick(object, ['name', 'userId']);
return Bookshelf.transaction((t) => {
return Runway.forge(data)
.save(null, {transaction: t})
.then((runway) => {
return runway.models().attach(object.models, {transaction: t});
})
})
.catch(err => {
winston.error('Error creating runway', {err: err});
throw err;
});
}
Logs:
Mon, 10 Oct 2016 06:07:59 GMT knex:tx trx1: Starting top level transaction
{ method: 'insert',
options: {},
timeout: false,
cancelOnTimeout: false,
bindings:
[ 2016-10-10T06:07:59.769Z,
'bf649bbf-c37f-426a-98e3-707e49eb17c6',
'my custom runway',
2016-10-10T06:07:59.769Z,
'66da84f6-45f4-4217-a995-dfb92cb246f1' ],
__knexQueryUid: 'c54606e4-7e4c-4a04-b66b-2f747df1ad6d',
sql: 'insert into `runways` (`created_at`, `id`, `name`, `updated_at`, `userId`) values (?, ?, ?, ?, ?)' }
{ method: 'insert',
options: {},
timeout: false,
cancelOnTimeout: false,
bindings:
[ 'f0a3bc21-2315-4b83-9cac-bab1fc019f1555',
'bf649bbf-c37f-426a-98e3-707e49eb17c6' ],
__knexQueryUid: '6125efce-3ef4-4327-a4ed-445634a26057',
sql: 'insert into `runways_models` (`modelId`, `runwayId`) values (?, ?)' }
Mon, 10 Oct 2016 06:07:59 GMT knex:tx trx1: releasing connection
2016-10-10T06:07:59.815Z ERROR [winston-fh] Error creating runway [METADATA]: {"err":{"message":"insert into `runways_models` (`modelId`, `runwayId`) values ('f0a3bc21-2315-4b83-9cac-bab1fc019f1555', 'bf649bbf-c37f-426a-98e3-707e49eb17c6') - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`figurehappy`.`runways_models`, CONSTRAINT `runways_models_modelid_foreign` FOREIGN KEY (`modelId`) REFERENCES `users` (`id`))","stack":"Error: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`figurehappy`.`runways_models`, CONSTRAINT `runways_models_modelid_foreign` FOREIGN KEY (`modelId`) REFERENCES `users` (`id`))\n at Query.Sequence._packetToError (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/sequences/Sequence.js:51:14)\n at Query.ErrorPacket (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/sequences/Query.js:83:18)\n at Protocol._parsePacket (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/Protocol.js:280:23)\n at Parser.write (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/Parser.js:74:12)\n at Protocol.write (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/Protocol.js:39:16)\n at Socket.<anonymous> (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/Connection.js:109:28)\n at emitOne (events.js:96:13)\n at Socket.emit (events.js:188:7)\n at readableAddChunk (_stream_readable.js:177:18)\n at Socket.Readable.push (_stream_readable.js:135:10)\n at TCP.onread (net.js:542:20)\n --------------------\n at Protocol._enqueue (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/protocol/Protocol.js:141:48)\n at Connection.query (/Users/Nim/Workspace/figurehappy/node_modules/mysql/lib/Connection.js:214:25)\n at /Users/Nim/Workspace/figurehappy/node_modules/knex/lib/dialects/mysql/index.js:124:18\n at Promise._execute (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/debuggability.js:284:9)\n at Promise._resolveFromExecutor (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:480:18)\n at new Promise (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:77:14)\n at Client._query (/Users/Nim/Workspace/figurehappy/node_modules/knex/lib/dialects/mysql/index.js:118:12)\n at Client.query (/Users/Nim/Workspace/figurehappy/node_modules/knex/lib/client.js:187:24)\n at Runner.<anonymous> (/Users/Nim/Workspace/figurehappy/node_modules/knex/lib/runner.js:129:36)\n at Runner.tryCatcher (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/util.js:16:23)\n at Runner.query (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/method.js:15:34)\n at /Users/Nim/Workspace/figurehappy/node_modules/knex/lib/runner.js:55:21\n at tryCatcher (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/util.js:16:23)\n at /Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/using.js:185:26\n at tryCatcher (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/util.js:16:23)\n at Promise._settlePromiseFromHandler (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:509:31)\n at Promise._settlePromise (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:566:18)\n at Promise._settlePromise0 (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:611:10)\n at Promise._settlePromises (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:690:18)\n at Promise._fulfill (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:635:18)\n at PromiseArray._resolve (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise_array.js:125:19)\n at PromiseArray._promiseFulfilled (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise_array.js:143:14)\n at Promise._settlePromise (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:571:26)\n at Promise._settlePromise0 (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:611:10)\n at Promise._settlePromises (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/promise.js:690:18)\n at Async._drainQueue (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/async.js:138:16)\n at Async._drainQueues (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/async.js:148:10)\n at Immediate.Async.drainQueues (/Users/Nim/Workspace/figurehappy/node_modules/bluebird/js/release/async.js:17:14)\n at runCallback (timers.js:570:20)\n at tryOnImmediate (timers.js:550:5)\n at processImmediate [as _immediateCallback] (timers.js:529:5)","code":"ER_NO_REFERENCED_ROW_2","errno":1452,"sqlState":"23000","index":0}}
insert into `runways_models` (`modelId`, `runwayId`) values ('f0a3bc21-2315-4b83-9cac-bab1fc019f1555', 'bf649bbf-c37f-426a-98e3-707e49eb17c6') - ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`figurehappy`.`runways_models`, CONSTRAINT `runways_models_modelid_foreign` FOREIGN KEY (`modelId`) REFERENCES `users` (`id`))
Error: ER_NO_REFERENCED_ROW_2: Cannot add or update a child row: a foreign key constraint fails (`figurehappy`.`runways_models`, CONSTRAINT `runways_models_modelid_foreign` FOREIGN KEY (`modelId`) REFERENCES `users` (`id`))
Sorry... this was a User error.
I should have written {transacting: t} instead of {transaction: t}.

Ownership process error running phoenix test in elixir 1.3.2

I am working through a phoenix tutorial but I have this error:
** (DBConnection.OwnershipError) cannot find ownership process for #PID<0.265.0>.
I am not using Task.start so nothing should be running asynchronously, and I thought that having the mode in the unless tag would be enough to prevent this error, in test/support/channel_case.ex:
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Watchlist.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, {:shared, self()})
end
:ok
end
So, I am curious how I resolve this error.
This is how I run it:
mix test test/integration/listing_movies_test.exs
I am using elixir 1.3.2
UPDATE
defmodule ListingMoviesIntegrationTest do
use ExUnit.Case, async: true
use Plug.Test
alias Watchlist.Router
#opts Router.init([])
test 'listing movies' do
movie = %Movie{name: "Back to the future", rating: 5}
|> Repo.insert! <== error happens here
conn = conn(:get, "/movies")
response = Router.call(conn, #opts)
assert response.status == 200
assert response.resp_body == movie
end
Full stack trace:
(db_connection) lib/db_connection.ex:718: DBConnection.checkout/2
(db_connection) lib/db_connection.ex:619: DBConnection.run/3
(db_connection) lib/db_connection.ex:463: DBConnection.prepare_execute/4
(ecto) lib/ecto/adapters/postgres/connection.ex:91: Ecto.Adapters.Postgres.Connection.execute/4
(ecto) lib/ecto/adapters/sql.ex:235: Ecto.Adapters.SQL.sql_call/6
(ecto) lib/ecto/adapters/sql.ex:454: Ecto.Adapters.SQL.struct/6
(ecto) lib/ecto/repo/schema.ex:397: Ecto.Repo.Schema.apply/4
(ecto) lib/ecto/repo/schema.ex:193: anonymous fn/11 in Ecto.Repo.Schema.do_insert/4
(ecto) lib/ecto/repo/schema.ex:124: Ecto.Repo.Schema.insert!/4
test/integration/listing_movies_test.exs:13: (test)
and in test_helper which is actually being called as I put in a debug statement:
ExUnit.start
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, :manual)
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, {:shared, self()})
use ExUnit.Case, async: true
use Plug.Test
You have code for setup hook in "test/support/channel_case.ex" but you are not using it anywhere in your test or at least it is not clear if you do use it. It would be helpful if you can add this:
IO.puts "#{inspect __MODULE__}: setup is getting called."
somewhere in your setup hook's code. This will make sure that the code actually runs. My suspicion from the comment you made in my previous answer this code is dead.
defmodule ListingMoviesIntegrationTest do
use ExUnit.Case, async: true
use Plug.Test
alias Watchlist.Router
setup do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Watchlist.Repo)
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, {:shared, self()})
:ok
end
#opts Router.init([])
test 'listing movies' do
movie = %Movie{name: "Back to the future", rating: 5}
|> Repo.insert! <== error happens here
conn = conn(:get, "/movies")
response = Router.call(conn, #opts)
assert response.status == 200
assert response.resp_body == movie
end
...
I got the same error and in my case on Elixir 1.8.2, Phoenix 1.4.1: after looking at this Elixir forum thread, I changed my test_helpers.exs to have the line below to have the adapter pool mode from manual to auto.
Ecto.Adapters.SQL.Sandbox.mode(MyApp.Repo, :auto)
You can read more about this about the modes and pool checkout and ownership on the Hex Ecto docs
I guess you are skipping this line
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, {:shared, self()})
because
iex(1)> unless true do
...(1)> IO.puts "test"
...(1)> end
nil
iex(2)> unless false do
...(2)> IO.puts "test"
...(2)> end
test
:ok
Did you try:
if tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Watchlist.Repo, {:shared, self()})
end

ActiveRecord 3.1 & SQL Exception on Debian

developing on Lion, packaged with sqlite3 3.7.5, i am having no problems.
i pushed to production (Debian Lenny w/ sqlite3 3.5.9) and i get the following SQL Exceptions
SQLite3::SQLException: no such column: taggings.tag_id: [query here]
i confirmed this by running the query manually from the rails dbconsole, and indeed sqlite 3.7.x returns results, but 3.5.x throws an error.
i am confident the query is fine, so is ActiveRecord 3.1 not compatible with sqlite 3.5? I am not seeing a newer version.
any ideas here?
Update
the failing query is...
SELECT tags.*, taggings.tags_count AS count
FROM "tags" JOIN (
SELECT taggings.tag_id, COUNT(taggings.tag_id) AS tags_count
FROM "taggings" INNER JOIN work ON work.id = taggings.taggable_id
WHERE (taggings.taggable_type = 'Work' AND taggings.context = 'tags')
AND (taggings.taggable_id IN(SELECT work.id FROM "work" )
)
GROUP BY taggings.tag_id HAVING COUNT(taggings.tag_id) > 0) AS taggings ON taggings.tag_id = tags.id
and my schema is
create_table "taggings", :force => true do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context"
t.datetime "created_at"
end
add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", :force => true do |t|
t.string "name"
end
FIX
well i never discovered the problem, but my assumption is that activerecord 3.1 is not compatible with sqlite 3.5.9.
although the last dpkg version for lenny is 3.5.9, i built 3.7.7 from source and it is processing the queries correctly now.

Resources