Problem with composite_primary_key Gem in Rails - ruby-on-rails

I'm using the composite primary keys gem from drnic and I've got a problem with it:
If I want to create a CourseOrder (with has a cpk) with the following command in my tests: course_order = CourseOrder.new(:daily_order => daily_orders(:daily_order_one_of_today_for_hans),:course => courses(:non_veg_2), :finished => false, :ordered_at => Time.now) I'll get the following error:
ActiveRecord::StatementInvalid: PGError: ERROR: null value in column "course_iddaily_order_id" violates not-null constraint
: INSERT INTO "course_orders" ("course_iddaily_order_id", "course_id", "ordered_at", "finished", "daily_order_id") VALUES (NULL, 489519433, '2011-03-01 10:19:27.169397', 'f', 594369222) RETURNING "course_iddaily_order_id"
I think that there is a course_iddaily_order_id is wrong, isn't it?
My Migration file looks like this:
class AddCourseOrder < ActiveRecord::Migration
def self.up
create_table :course_orders, :primary_key => [:course_id, :daily_order_id] do |table|
table.integer :course_id
table.integer :daily_order_id
table.datetime :ordered_at, :null => false
table.boolean :finished, :default => false, :null => false
end
end
def self.down
drop_table :course_orders
end
end
The resulting schema part looks like this:
create_table "course_orders", :primary_key => "course_iddaily_order_id", :force => true do |t|
t.integer "course_id", :null => false
t.integer "daily_order_id", :null => false
t.datetime "ordered_at", :null => false
t.boolean "finished", :default => false, :null => false
end
My Model looks like this:
class CourseOrder < ActiveRecord::Base
set_primary_keys :course_id, :daily_order_id
belongs_to :course
belongs_to :daily_order
end
I don't know whats wrong here, can you help?

I guess the create_table method doesn't takes an array for :primary_key option. I guess you can omit setting it.

Related

Custom helper methods for Rails 3.2 Migrations

I'm trying to access helper methods inside my migrations. I can't seem to get anything to work when accomplishing something like this:
Migration File:
require File.expand_path('lib/migration_helper')
include MigrationHelper
class NewTable < ActiveRecord::Migration
def change
create_table :new_table do |t|
t.boolean :boolean
safe_delete_methods
end
end
end
Migration helper in /lib directory
#Custom Methods available to Migrations
module MigrationHelper
def safe_delete_methods
return
t.boolean :deleted, :default => 0, :null => false
t.integer :deleted_by, :default => 0, :null => false
t.datetime :deleted_at
end
end
Thank you for any answers
module MigrationHelper
def safe_delete_methods
t.boolean :deleted, :default => 0, :null => false
t.integer :deleted_by, :default => 0, :null => false
t.datetime :deleted_at
end
end
cann't use return before the code.

Do I need to create an assocation table for a :has_many :through association?

I'm trying to use a :has_many :through type association, but I'm getting the following error:
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: work_units.developer_id:
Many other posts about this sort of thing have just had spelling mistakes, but I've checked mine.
class Developer < ActiveRecord::Base
attr_accessible :skype_name, :language_ids, :user_attributes
has_many :work_units
has_many :projects, :through => :work_units
...
end
class Project < ActiveRecord::Base
attr_accessible :complete, :description, :finalised, :price
has_many :work_units
has_many :developers, :through => :work_units
...
end
class WorkUnit < ActiveRecord::Base
attr_accessible :hours_worked
belongs_to :project
belongs_to :developer
end
I've run db:migrate and it didn't complain. I did make a mistake and had to rollback the db then re-migrate, but I think I did it right. I use the annotate gem and it doesn't show any of the relationship ids I'd expect. So, do I need to create a WorkUnits table or am I missing something? The rails guide didn't mention manually making tables.
Edit
Here's the migration I used to create the WorkUnit model and stuff:
class CreateWorkUnits < ActiveRecord::Migration
def change
create_table :work_units do |t|
t.integer :hours_worked, :default => 0
t.timestamps
end
end
end
Edit 2
Snippets from my schema.rb:
create_table "work_units", :force => true do |t|
t.integer "hours_worked", :default => 0
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "projects", :force => true do |t|
t.string "description"
t.decimal "price", :precision => 8, :scale => 2
t.boolean "complete", :default => false
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
Similarly for :developers. So, why doesn't my migration add the association information for me?
Your WorkUnit migration should look like this:
class CreateWorkUnits < ActiveRecord::Migration
def change
create_table :work_units do |t|
t.integer :hours_worked, :default => 0
t.references :developer
t.references :project
t.timestamps
end
add_index :work_units, :developer_id
add_index :work_units, :project_id
end
end
You need to add the foreign keys to your work_units table.
class CreateWorkUnits < ActiveRecord::Migration
def change
create_table :work_units do |t|
t.integer :hours_worked, :default => 0
t.integer :project_id, null: false
t.integer :developer_id, null: false
t.timestamps
end
add_index :work_units, :project_id
add_index :work_units, :developer_id
end
end
Another way:
class CreateWorkUnits < ActiveRecord::Migration
def change
create_table :work_units do |t|
t.integer :hours_worked, :default => 0
t.belongs_to :project
t.belongs_to :developer
t.timestamps
end
add_index :work_units, :project_id
add_index :work_units, :developer_id
end
end
You can also define these fields when generating your model, then they'll be added to the migration automatically as show in the second snippet.
$ rails g model WorkUnit hours_worked:integer project:belongs_to developer:belongs_to
Hope that helps.
A table for WorkUnit needs to exist, whether that means it migration was automatically generated via scaffolding or if the migration was manually written by you.
If you don't have a migration yet that creates that table, you'll need to create that migration because the table does need to exist.
You do need a work_units table with a project_id and developer_id column.
Have a look at http://xyzpub.com/en/ruby-on-rails/3.2/activerecord_datenbank_anlegen.html if you don't know how to create a table.

How do I write the opposite of this migration?

My migration right now :
class CreateActivities < ActiveRecord::Migration
def self.up
create_table :activities do |t|
t.integer :account_id, :null => false
t.integer :target_id, :null => false
t.string :target_type, :null => false
t.string :event_type, :null => false
t.integer :employee_id
t.string :name
t.timestamps
end
add_index :activities, [:target_id, :target_type]
With this I can now call a target like so :
Activity.first.target
And it will bring up the target_id, based on the target_type.
How would I do the opposite of that so that I can select a target, and if it has any associated Activities, they will show up?
Like so :
Job.find(1234).activities
# Where Job.find(1234) is the target_id of many activities.
If I understand right, this should do it:
class Job < ActiveRecord::Base
has_many :activities, :conditions => ['target_type = ?', 'Job'], :as => :target
end

Getting ActiveRecord::RecordNotUnique but then not able to find the existing record

I have something like the following code. (Model names changed as they're not important to what's happening.)
The #find_or_create_bar_for_blah_id works fine most of the time. Occasionally it will return nil though and I'm not sure why.
It's some kind of race condition as the problem happens in resque jobs that run as part of our app.
Any clues as to how #find_or_create_bar_for_blah_id could return nil?
class Foo < ActiveRecord::Base
has_many :bars, :dependent => :destroy
def find_or_create_bar_for_blah_id(locale_id)
begin
bars.where(:blah_id => blah_id).first || bars.create!(:blah_id => blah_id)
rescue ActiveRecord::RecordNotUnique
bars.where(:blah_id => blah_id).first
end
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
validates_uniqueness_of :blah_id, :scope => :foo_id
end
# db/schema.rb
create_table "bars", :force => true do |t|
t.integer "foo_id"
t.integer "blah_id"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "bars", ["foo_id", "blah_id"], :name => "index_bars_on_foo_id_and_blah_id", :unique => true
add_index "bars", ["foo_id"], :name => "index_bars_on_foo_id"
create_table "foos", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "foos", ["name"], :name => "index_foos_on_name"
Doh! This was because we were using update_attribute in part of the code, which of course doesn't run AR validations. embarrassed face

Using build with has_many :through

I have an Entry model and a Category model, where an Entry can have many Categories (through EntryCategories):
class Entry < ActiveRecord::Base
belongs_to :journal
has_many :entry_categories
has_many :categories, :through => :entry_categories
end
class Category < ActiveRecord::Base
has_many :entry_categories, :dependent => :destroy
has_many :entries, :through => :entry_categories
end
class EntryCategory < ActiveRecord::Base
belongs_to :category
belongs_to :entry
end
When creating a new Entry, I create it by calling #journal.entries.build(entry_params), where entry_params is the parameters from the entry form. If any categories are selected, however, I get this error:
ActiveRecord::HasManyThroughCantDissociateNewRecords in Admin/entriesController#create
Cannot dissociate new records through 'Entry#entry_categories' on '#'. Both records must have an id in order to delete the has_many :through record associating them.
Note that the '#' on the second line is verbatim; it doesn't output an object.
I have tried naming my categories selectbox on the form to categories and category_ids but neither make a difference; if either is in the entry_params, the save will fail. If no categories are selected, or I remove categories from entry_params (#entry_attrs.delete(:category_ids)), the save works properly, but the categories don't save, obviously.
It seems to me that the problem is that an EntryCategory record is attempting to be made before the Entry record is saved? Shouldn't build be taking care of that?
Update:
Here's the relevant parts of schema.rb, as requested:
ActiveRecord::Schema.define(:version => 20090516204736) do
create_table "categories", :force => true do |t|
t.integer "journal_id", :null => false
t.string "name", :limit => 200, :null => false
t.integer "parent_id"
t.integer "lft"
t.integer "rgt"
end
add_index "categories", ["journal_id", "parent_id", "name"], :name => "index_categories_on_journal_id_and_parent_id_and_name", :unique => true
create_table "entries", :force => true do |t|
t.integer "journal_id", :null => false
t.string "title", :null => false
t.string "permaname", :limit => 60, :null => false
t.text "raw_body", :limit => 2147483647
t.datetime "created_at", :null => false
t.datetime "posted_at"
t.datetime "updated_at", :null => false
end
create_table "entry_categories", :force => true do |t|
t.integer "entry_id", :null => false
t.integer "category_id", :null => false
end
add_index "entry_categories", ["entry_id", "category_id"], :name => "index_entry_categories_on_entry_id_and_category_id", :unique => true
end
Also, saving an entry with categories works fine in the update action (by calling #entry.attributes = entry_params), so it does seem to me that the problem is only based on the Entry not existing at the point that the EntryCategory records are attempted to be created.
I tracked down the cause of this error to be within the nested_has_many_through plugin. It seems that the version I had installed was buggy; after updating to the most recent version, my build works again.
Why do you call
self.journal.build(entry_params)
instead of
Entry.new(entry_params)
If you need to create a new entry associated to a specific Journal, given a #journal, you can do
#yournal.entries.build(entry_params)

Resources