【发布时间】:2012-09-12 19:12:00
【问题描述】:
这是我正在使用的 3 个模型:
user.rb:
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# name :string(255)
# email :string(255)
# remember_token :string(255)
# password_digest :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :password_confirmation
has_many :jobs
has_many :restaurants, :through => :jobs
end
job.rb
# == Schema Information
#
# Table name: jobs
#
# id :integer not null, primary key
# restaurant_id :integer
# shortname :string(255)
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Job < ActiveRecord::Base
attr_accessible :restaurant_id, :shortname, :user_id
belongs_to :user
belongs_to :restaurant
has_many :shifts
end
餐厅.rb:
# == Schema Information
#
# Table name: restaurants
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Restaurant < ActiveRecord::Base
attr_accessible :name
has_many :jobs
has_many :users, :through => :jobs
has_many :positions
end
我的场景是用户已经创建并输入到用户表中,但是现在用户想要:
- 可能创建一家新餐厅(如果尚不存在)
- 通过作业表在用户和餐厅之间创建链接,并
- 可能同时在作业表中创建昵称
我将在表单中使用嵌套模型来完成此操作,但是我现在删除了所有与此相关的代码。原因是我试图从 Restaurants_Controller 中创建记录,如您所见,它位于“链”的底部。仔细想想,这似乎是错误的。除了在作业模型中链接 user_id 之外,我可以让 rails 为所有事情做这件事。
无论如何,我认为我对 Rails 的理解并不高。保存上述内容的逻辑应该在哪里(作为一个人在表单上点击“提交”的结果)?
【问题讨论】:
标签: ruby-on-rails controller nested-attributes