Rails has_many:为什么create_model不起作用?

Bra*_*don 0 ruby-on-rails associations has-many ruby-on-rails-3

我想我在这里错过了一些简单的东西......但是无法弄明白.

class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me
  has_many :events
end

class Event < ActiveRecord::Base
  attr_accessible :start, :end, :all_day, :url
  belongs_to :user
end

u1 = User.create name: "Bob", email: "bob@what.com", password: "asdfasdf"
u1.create_event(start: 3.days.from_now)
Run Code Online (Sandbox Code Playgroud)

- >

undefined method `create_event' for #<User:0x007f918cbbf7b8>
Run Code Online (Sandbox Code Playgroud)

然而,

u1.events << Event.create!(start: 3.days.from_now)
Run Code Online (Sandbox Code Playgroud)

作品!

Tha*_*anh 6

您已定义has_many关联:

has_many :events
Run Code Online (Sandbox Code Playgroud)

因此,如果要创建对象,可以使用以下方法:

# create new object, but not insert to database
u1.events.build(...)

# create new object and auto call `save` method to insert to database
u1.events.create(...)
Run Code Online (Sandbox Code Playgroud)

您使用u1.create_event,这将在您定义has_one关联时更正:

has_one :event
Run Code Online (Sandbox Code Playgroud)

所以,你将有这些方法来创建对象:

# create new object, but not insert to database
u1.build_event(...)

# create new object and auto call `save` method to insert to database
u1.create_event(...)
Run Code Online (Sandbox Code Playgroud)