I'm relatively new to Rails (4, Ruby 2.0) and currently have a has_many + belongs_to association that I'm working with. The association that I'm trying to model is a 'Day' having several 'Timeslots' and each Timeslot belonging to a Day.
My models look like this:
Day.rb
class Day < ActiveRecord::Base
has_many :timeslots
belongs_to :calendar
end
Timeslot.rb
class Timeslot < ActiveRecord::Base
has_many :events
belongs_to :day
validates_presence_of :start_time
validates_presence_of :end_time
validates_presence_of :day_id
end
Schemas for Day and Timeslot:
create_table "days", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "timeslots", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.time "start_time"
t.time "end_time"
t.integer "day_id"
end
The issue that I'm seeing is that I can't get a Timeslot object to save to the DB correctly:
In the console:
d = Day.new
=> #<Day id: nil, created_at: nil, updated_at: nil, date: nil>
d.id = 20140322
=> 20140322
d.save
(0.1ms) begin transaction
SQL (22.2ms) INSERT INTO "days" ("created_at", "date", "id", "updated_at") VALUES (?, ?, ?, ?) [["created_at", Sat, 22 Mar 2014 21:28:27 PDT -07:00], ["id", 20140322], ["updated_at", Sat, 22 Mar 2014 21:28:27 PDT -07:00]]
(6.8ms) commit transaction
=> true
Day.all
Day Load (0.3ms) SELECT "days".* FROM "days"
=> #<ActiveRecord::Relation [#<Day id: 20140322, created_at: nil, updated_at: nil>]>
t = Timeslot.new
=> #<Timeslot id: nil, created_at: nil, updated_at: nil, start_time: nil, end_time: nil, day_id: nil>
t.start_time = Time.now
2014-03-22 21:28:52 -0700
t.end_time = Time.now
2014-03-22 21:28:57 -0700
t.day_id = 20140322
=> 20140322
t.save
(0.1ms) begin transaction
SQL (0.8ms) INSERT INTO "timeslots" ("created_at", "day_id", "end_time", "start_time", "updated_at") VALUES (?, ?, ?, ?, ?) [["created_at", Sat, 22 Mar 2014 21:29:06 PDT -07:00], ["day_id", 20140322], ["end_time", 2014-03-22 21:28:57 -0700], ["start_time", 2014-03-22 21:28:52 -0700], ["updated_at", Sat, 22 Mar 2014 21:29:06 PDT -07:00]]
(7.6ms) commit transaction
=> true
# Here's the problem
Day.all
Day Load (0.2ms) SELECT "days".* FROM "days"
=> #<ActiveRecord::Relation [#<Day id: 20140322, created_at: nil, updated_at: nil>]>
2.0.0-p247 :015 > Timeslot.all
Timeslot Load (0.2ms) SELECT "timeslots".* FROM "timeslots"
=> #<ActiveRecord::Relation [#<Timeslot id: 2, created_at: nil, updated_at: nil, start_time: nil, end_time: nil, day_id: 20140322>]>
a = Day.all.first
Day Load (0.2ms) SELECT "days".* FROM "days" ORDER BY "days"."id" ASC LIMIT 1
=> #<Day id: 20140322, created_at: nil, updated_at: nil>
a.timeslots
Timeslot Load (0.3ms) SELECT "timeslots".* FROM "timeslots" WHERE "timeslots"."day_id" = ? [["day_id", 20140322]]
=> #]>
The fact is that the Timeslot objects just don't seem be created properly. I'm not sure why this is happening.
There are several things I don't understand in your files, and I think you should use the ruby command line tools to generate your files to be sure not to do any mistake. For instance, your created_At and updated_at are not normal, they should be filled automatically and they are not.
I suggest you delete your files and launch those commands
rails g model day calendar:references
rails g model timeslot start_time:time end_time:time day:references
Then you add your association to the models
class Day < ActiveRecord::Base
has_many :timeslots
belongs_to :calendar
end
class Timeslot < ActiveRecord::Base
has_many :events
belongs_to :day
validates_presence_of :start_time
validates_presence_of :end_time
# validates_presence_of :day_id #Remove this line for now
end
And you can launch rake db:migrate and try again (by the way Day.all.first is the same as Day.first and instead of t.day_id = ..., try t.day = Day.first
Related
Whenever I instantiate a new ActiveRecord model (one that has not been persisted to the database) and attempt to access some various associations on the built model, the Rails query builder will sometimes:
Add a (1=0) predicate to the where clause of the query.
Add a 'distinct` clause to the select statement.
I think this only occurs when the has_many :through association is joining two or more tables.
I want to know why it adds the (1=0) predicate as well as the distinct clause. For the (1=0) predicate, it shouldn't matter if the new model has been saved to the database or not (right?). I have no idea why the distinct clause is being added.
I have a simple example below.
class Assignment < ActiveRecord::Base
has_many :assignment_attachments
has_many :attachments, through: :assignment_attachments
end
class AssignmentAttachment < ActiveRecord::Base
belongs_to :assignment
belongs_to :attachment
end
class Attachment < ActiveRecord::Base
has_many :assignment_attachments
has_many :assignments, through: :assignment_attachments
end
class Submission < ActiveRecord::Base
belongs_to :assignment
has_many :assignment_attachments, through: :assignment
has_many :attachments, through: :assignment
end
s = Submission.new(assignment: Assignment.first)
s.assignment #=> #<Assignment ...>
s.assignment_attachments #=> [#AssignmentAttachment id: '1'>, #AssignmentAttachment assignment_id: '1', attachment_id: '1' ...>]
s.attachments #=> []
Here's the sql query for s.attachments:
SELECT DISTINCT attachments.*
FROM attachments
INNER JOIN assignment_attachments ON attachments.id = assignment_attachments.attachment_id
INNER JOIN assignments ON assignment_attachments.assignment_id = assignments.id
WHERE assignments.id = 'a0dbfdc7-0d67-4aad-ad06-6a7a5a91d2d0' AND (1=0)
Located somewhere deep in one of the subtrees of the abstract syntax tree that arel builds:
# the 'distinct' select clause
#<Arel::Nodes::SelectCore:0x007ffe43d45be0
#groups=[],
#having=nil,
#projections=
[#<struct Arel::Attributes::Attribute
relation=
#<Arel::Table:0x007ffe45a7be58
#aliases=[],
#columns=nil,
#engine=
Attachment(name: string, description: text, created_at: datetime, updated_at: datetime, required: boolean, id: uuid, slug: string, file_types: string),
#name="attachments",
#primary_key=nil,
#table_alias=nil>,
name="*">],
#set_quantifier=#<Arel::Nodes::Distinct:0x007ffe43d44dd0>,
...
# the (1=0) predicate
#wheres=
[#<Arel::Nodes::And:0x007ffe43d45028
#children=
[#<Arel::Nodes::Equality:0x007ffe45958788
#left=
#<struct Arel::Attributes::Attribute
relation=
#<Arel::Table:0x007ffe45958e68
#aliases=[],
#columns=nil,
#engine=ActiveRecord::Base,
#name="assignments",
#primary_key=nil,
#table_alias=nil>,
name="id">,
#right=#<Arel::Nodes::BindParam:0x007ffe45958878>>,
#<Arel::Nodes::Grouping:0x007ffe43d45050 #expr="1=0">]>]
Do you know why arel is building the distinct clause and the (1=0) predicate? I can use some workarounds to get what I want - however, I would love to be able to investigate and find out why and how this tree is built.
Thanks for any/all advice.
Note this is an edit to reflect new info from OP. With the new info I have recreated the scenario in a fresh project by copy and pasting OP's code plus the following migration.
Migration:
class CreateAttachments < ActiveRecord::Migration
def change
create_table :attachments do |t|
t.integer :assignment_attachment_id
t.timestamps null: false
end
create_table :assignments do |t|
t.integer :assignment_attachment_id
t.timestamps null: false
end
create_table :assignment_attachments do |t|
t.integer :assignment_id
t.integer :attachment_id
t.timestamps null: false
end
create_table :submissions do |t|
t.integer :assignment_id
t.timestamps null: false
end
end
end
Works fine when associations exist in DB
When I save the Attachment and Assignment models to which I will associate my Submission model s, even though never save s, it works fine.
irb(main):001:0> attachment = Attachment.new
=> #<Attachment id: nil, assignment_attachment_id: nil, created_at: nil, updated_at: nil>
irb(main):003:0> assignment = Assignment.new
=> #<Assignment id: nil, assignment_attachment_id: nil, created_at: nil, updated_at: nil>
irb(main):005:0> assignment.attachments << attachment
=> #<ActiveRecord::Associations::CollectionProxy [#<Attachment id: nil, assignment_attachment_id: nil, created_at: nil, updated_at: nil>]>
irb(main):006:0> assignment.save
(0.2ms) begin transaction
SQL (1.5ms) INSERT INTO "assignments" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-10-14 17:10:34.936929"], ["updated_at", "2015-10-14 17:10:34.936929"]]
SQL (0.6ms) INSERT INTO "attachments" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-10-14 17:10:34.944453"], ["updated_at", "2015-10-14 17:10:34.944453"]]
SQL (0.3ms) INSERT INTO "assignment_attachments" ("assignment_id", "attachment_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["assignment_id", 1], ["attachment_id", 1], ["created_at", "2015-10-14 17:10:34.947481"], ["updated_at", "2015-10-14 17:10:34.947481"]]
(0.8ms) commit transaction
=> true
irb(main):007:0> s = Submission.new(assignment: Assignment.first)
Assignment Load (0.2ms) SELECT "assignments".* FROM "assignments" ORDER BY "assignments"."id" ASC LIMIT 1
=> #<Submission id: nil, assignment_id: 1, created_at: nil, updated_at: nil>
irb(main):008:0> s.assignment
=> #<Assignment id: 1, assignment_attachment_id: nil, created_at: "2015-10-14 17:10:34", updated_at: "2015-10-14 17:10:34">
irb(main):009:0> s.assignment_attachments
AssignmentAttachment Load (0.2ms) SELECT "assignment_attachments".* FROM "assignment_attachments" INNER JOIN "assignments" ON "assignment_attachments"."assignment_id" = "assignments"."id" WHERE "assignments"."id" = ? [["id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<AssignmentAttachment id: 1, assignment_id: 1, attachment_id: 1, created_at: "2015-10-14 17:10:34", updated_at: "2015-10-14 17:10:34">]>
irb(main):010:0> s.attachments
Attachment Load (0.2ms) SELECT "attachments".* FROM "attachments" INNER JOIN "assignment_attachments" ON "attachments"."id" = "assignment_attachments"."attachment_id" INNER JOIN "assignments" ON "assignment_attachments"."assignment_id" = "assignments"."id" WHERE "assignments"."id" = ? [["id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Attachment id: 1, assignment_attachment_id: nil, created_at: "2015-10-14 17:10:34", updated_at: "2015-10-14 17:10:34">]>
irb(main):011:0> s.attachments.to_sql
=> "SELECT \"attachments\".* FROM \"attachments\" INNER JOIN \"assignment_attachments\" ON \"attachments\".\"id\" = \"assignment_attachments\".\"attachment_id\" INNER JOIN \"assignments\" ON \"assignment_attachments\".\"assignment_id\" = \"assignments\".\"id\" WHERE \"assignments\".\"id\" = 1"
Generates "1=0" predicate when there are no associations
If I do not specify any associations to the Submission instance, however, when I ask for its attachments, the query does get the 1=0 predicate. As this post describes, the 1=0 predicate is added when you are trying to retrieve records that join on an array of ids that is actually empty. This is true here, since we made sure that there are no assignment ids we can use for joining to attachment.
irb(main):007:0> Submission.new.attachments.to_sql
=> "SELECT \"attachments\".* FROM \"attachments\" INNER JOIN \"assignment_attachments\" ON \"attachments\".\"id\" = \"assignment_attachments\".\"attachment_id\" INNER JOIN \"assignments\" ON \"assignment_attachments\".\"assignment_id\" = \"assignments\".\"id\" WHERE \"assignments\".\"id\" = NULL AND (1=0)"
irb(main):008:0>
Notice how it says WHERE \"assignments\".\"id\" = NULL. It can't leave it at that because it doesn't want to assume that there aren't null ids in the assignments table that would cause it to return false positives. With the additional 1=0 predicate, you are ensured to get the correct answer: an empty result.
DISTINCT
I am unable to reproduce a scenario where DISTINCT appears.
According to the Rails' guide, the has_many :through asssociation is used for the classic many-to-many connection.
In this context, I the (1=0) predicate makes sense. Let me explain with an example.
Consider the Assignment, AssignmentAttachment, and Attachment models from the question above:
Assignment.new.attachments.to_sql
SELECT attachments.*
FROM attachments INNER JOIN assignment_attachments ON attachments.id = assignment_attachments.attachment_id
WHERE assignment_attachments.assignment_id = NULL AND (1=0)
In code above, a new Assignment instance, not yet persisted to the database, tries to access attachments associated with it. Obviously, since the model has not been saved, there are no attachments associated with it and the query builder adds a (1=0) predicate.
I still don't know why the DISTINCT clause doesn't get added to the query for a classic many-to-many relationship but does when the has_many :through relationship goes through >= 2 tables.
I'm trying to model a system where each user may have many emails (at least one).
Following good normalization rules I created two migrations (some fields removed for brevity):
create_table :users do |t|
end
create_table :user_emails do |t|
t.integer :user_id, null: false
t.string :email, null: false
end
add_index :user_emails, :email, :unique => true
add_foreign_key :user_emails, :users, dependent: :delete
and the following rails models:
class User < ActiveRecord::Base
has_many :emails, class_name: 'UserEmail', dependent: :destroy
def self.find_by_email(email)
UserEmail.find_by(email: email).try(:user)
end
validate do
if emails.count < 1
errors.add(:emails, "is empty")
end
end
end
class UserEmail < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id, :email
validates_uniqueness_of :email
end
Now I am not able to create any of those. User cannot be created since it requires at least an UserEmail. At the same time, UserEmail cannot be created beforehand since it requires an user_id.
I believe I have tried any combination of #user.emails.build and #user.emails << e that I can think of.
How can I solve this really simple problem without renouncing to data consistency (one is saved and the other is not)?
P.s.: I tought that maybe relaxing the validations and using transactions may solve the problem consistently. However I've never used transactions in rails, so any help is really appreciated.
Thanks
validates_presence_of :user_id only check for any valid integer which might not be a valid user.
But if you use validates_presence_of :user and validates_presence_of :emails, they will check the user and emails association are valid and not blank.
Also, when you are trying to create the user and the associated email, you are able to do the following code on application level.
user = User.new(name: 'user name')
user.emails.build(email_address: 'email address') #build(email: '') for your case.
Then, you can save to database with
user.save!
Below is the code I tested with.
class User < ActiveRecord::Base
has_many :emails, class_name: 'UserEmail', dependent: :destroy
validates_presence_of :emails, :message => 'User should have at least one email address.'
end
class UserEmail < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
validates_presence_of :email_address
end
[40] pry(main)> u = User.create!(name: 'doh')
(0.1ms) begin transaction
(0.0ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Emails User should have at least one email address.
[1] pry(main)> u = User.new(name: 'nice')
=> #<User id: nil, name: "nice", created_at: nil, updated_at: nil>
[2] pry(main)> u.emails.build(email_address: 'hello#world.blah')
=> #<UserEmail id: nil, user_id: nil, email_address: "hello#world.blah", created_at: nil, updated_at: nil>
[3] pry(main)> u.save!
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "users" ("created_at", "name", "updated_at") VALUES (?, ?, ?) [["created_at", "2014-07-26 10:14:52.184245"], ["name", "nice"], ["updated_at", "2014-07-26 10:14:52.184245"]]
SQL (0.2ms) INSERT INTO "user_emails" ("created_at", "email_address", "updated_at", "user_id") VALUES (?, ?, ?, ?) [["created_at", "2014-07-26 10:14:52.189757"], ["email_address", "hello#world.blah"], ["updated_at", "2014-07-26 10:14:52.189757"], ["user_id", 5]]
(0.7ms) commit transaction
=> true
[4] pry(main)> u.emails.count
(0.2ms) SELECT COUNT(*) FROM "user_emails" WHERE "user_emails"."user_id" = ? [["user_id", 5]]
=> 1
[5] pry(main)> u.id
=> 5
[6] pry(main)> u.name
=> "nice"
[7] pry(main)> u.emails
=> [#<UserEmail id: 4, user_id: 5, email_address: "hello#world.blah", created_at: "2014-07-26 10:14:52", updated_at: "2014-07-26 10:14:52">]
[8] pry(main)> u
=> #<User id: 5, name: "nice", created_at: "2014-07-26 10:14:52", updated_at: "2014-07-26 10:14:52">
[19] pry(main)> UserEmail.create!(email_address: 'test#test.org')
(0.1ms) begin transaction
(0.1ms) rollback transaction
ActiveRecord::RecordInvalid: Validation failed: User can't be blank
Hope this helps.
I just realized that I adding a NOT NULL constraint on the storage layer is sufficient. I can remove the :user_id presence validation and have the same consistency behavior, with the exception that it now works.
However this looks quite hacky from the rails POW. Any better solution is still really appreciated...
The Issue
The rails console will not save my record to the database if it has a belongs_to association.
2.1.1 :002 > Track.create name: 'asdfasdf'
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "records" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-06-12 15:58:20.868095"], ["updated_at", "2014-06-12 15:58:20.868095"]]
(45.9ms) commit transaction
=> #<Track id: nil, record_id: 1, name: "asdfasdf", created_at: nil, updated_at: nil>
class Record < ActiveRecord::Base
has_many :tracks
accepts_nested_attributes_for :tracks, allow_destroy: true
end
class Track < ActiveRecord::Base
belongs_to :record
end
class CreateRecords < ActiveRecord::Migration
def change
create_table :records do |t|
t.string :title
t.timestamps
end
end
end
class CreateTracks < ActiveRecord::Migration
def change
create_table :tracks do |t|
t.belongs_to :record
t.string :name
t.timestamps
end
end
end
As you can see the :id field is nil. The :record_id field gets incremented instead.
I have tried resetting the primary key and the issue still persists. This is however not my main beef because the record is not even saved after the insert.
2.1.1 :003 > Track.last
Track Load (0.3ms) SELECT "tracks".* FROM "tracks" ORDER BY "tracks"."id" DESC LIMIT 1
=> nil
This is an issue because it prevents me from using nested forms like this one. Indecently when I download and run that rails app it works perfectly.
2.1.1 :002 > Answer.create content: 'swwaaagggggs'
(0.2ms) begin transaction
SQL (0.8ms) INSERT INTO "answers" ("content", "created_at", "updated_at") VALUES (?, ?, ?) [["content", "swwaaagggggs"], ["created_at", "2014-06-12 16:46:04.989529"], ["updated_at", "2014-06-12 16:46:04.989529"]]
(58.9ms) commit transaction
=> #<Answer id: 3, question_id: nil, content: "swwaaagggggs", created_at: "2014-06-12 16:46:04", updated_at: "2014-06-12 16:46:04">
Yet when I recreate it exactly myself I run into the same problem.
Strangely
If I rollback migrations and remove the association I get this.
2.1.1 :003 > Track.create name: 'swagger'
(0.2ms) begin transaction
SQL (0.7ms) INSERT INTO "records" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2014-06-12 16:06:12.443845"], ["updated_at", "2014-06-12 16:06:12.443845"]]
(0.2ms) rollback transaction
ActiveModel::MissingAttributeError: can't write unknown attribute `record_id'
class Record < ActiveRecord::Base
end
class Track < ActiveRecord::Base
end
class CreateRecords < ActiveRecord::Migration
def change
create_table :records do |t|
t.string :title
t.timestamps
end
end
end
class CreateTracks < ActiveRecord::Migration
def change
create_table :tracks do |t|
t.string :name
t.timestamps
end
end
end
Note the reference to :record_id when the column no longer exists
I am at a loss.
Google has run out of pages and nobody else seem to have this issue which had led me to think that there has been something wrong with my code for the last 2 days; "something this well documented shouldn't be this hard," I thought. If anyone can help me figure this out I would be grateful.
Please let me know if you require more information this is the first time I have felt the need to post to StackOverflow.
Record is probably a reserved key word in rails ?
http://reservedwords.herokuapp.com/words/record?q[word_or_notes_cont]=record
I have a class as follows:
class Player < ActiveRecord::Base
attr_accessor :name, :rating, :team_name
end
So I ran 'bundle exec rails console' and then
Player.create(:name => "Ben", :rating => 5, :team_name => "Brown")
However, this is what I get back:
(0.1ms) begin transaction
SQL (7.0ms) INSERT INTO "players" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Sat, 29 Mar 2014 04:24:31 UTC +00:00], ["updated_at", Sat, 29 Mar 2014 04:24:31 UTC +00:00]]
(0.9ms) commit transaction
=> #<Player id: 1, name: nil, rating: nil, team_name: nil, created_at: "2014-03-29 04:24:31", updated_at: "2014-03-29 04:24:31">
Why does the object that's created not have the properties I've assigned it? This strikes me as really strange...
Any guidance on this one?
Thanks,
Mariogs
Player.create(:name => "Ben", :rating => 5, :team_name => "Brown")
Here you are mass assigning attributes name, rating and team_name
So you need to tell Player model that above attributes can be mass assigned.
to allows mass assignment, you have to pass those attributes to attr_accessible method.
attr_accessor is used for creating getter and setter methods.
And getter and setter methods for database attributes are dynamically created, you don't need to create it.
so change
attr_accessor :name, :rating, :team_name
to
attr_accessible :name, :rating, :team_name
(I could probably think of a better title for this and open to suggestions)
I am trying to call this in my NotesController, testing it in rails console:
?> u = User.first
User Load (1.6ms) SELECT "users".* FROM "users" LIMIT 1
=> #<User id: 2, email: nil, password: nil, linkedin_url: nil, created_at: "2012-06-17 05:54:44", updated_at: "2012-06-17 05:54:44", liid: "7fB-pQGIQi">
>> c = u.contacts.first
Contact Load (2.0ms) SELECT "contacts".* FROM "contacts" WHERE "contacts"."user_id" = 2 LIMIT 1
=> #<Contact id: 8, user_id: 2, created_at: "2012-06-19 01:23:45", updated_at: "2012-06-19 01:23:45">
>> c.notes.create!(:body => "this is a note")
(0.5ms) BEGIN
SQL (23.3ms) INSERT INTO "notes" ("body", "contact_id", "created_at", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["body", "this is a note"], ["contact_id", 8], ["created_at", Thu, 21 Jun 2012 05:42:21 UTC +00:00], ["updated_at", Thu, 21 Jun 2012 05:42:21 UTC +00:00], ["user_id", nil]]
(1.7ms) COMMIT
=> #<Note id: 4, created_at: "2012-06-21 05:42:21", updated_at: "2012-06-21 05:42:21", body: "this is a note", user_id: nil, contact_id: 8>
The problem is in the last line where it says that the Note created has a "user_id: nil". I'm wondering what I'm missing that is not allowing the note to properly get the user_id from the contact user_id? I can think of a quick fix, to set the user_id on the note object, but it seems as though it could fetch it from the contact_id, am I wrong?
Here are my models in case this is helpful:
class Contact < ActiveRecord::Base
attr_accessible :user_id
belongs_to :user
has_many :notes
end
class User < ActiveRecord::Base
attr_accessible :password, :liid
has_many :contacts
has_many :notes, :through => :contacts
end
class Note < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :contact
belongs_to :user
end
Thanks for the help!
Your Note also needs to belong to your User:
class Note < ActiveRecord::Base
attr_accessible :title, :body
belongs_to :contact
belongs_to :user
end
Rails will only automatically set the foreign_key of the parent object, and not the parent object's parent like you want. So you'll have to set that attribute manually:
c.notes.create!(:body => "this is a note", :user_id => c.user_id)