【发布时间】:2017-10-20 17:13:54
【问题描述】:
我是 Rails 新手,我可能在这里遗漏了一些非常基本的东西:
用户可以为公司的分支机构和部门创建联系人
Branch.rb
class Branch < ApplicationRecord
belongs_to :company
has_many :contacts
end
Division.rb
class Division < ApplicationRecord
belongs_to :company
has_many :contacts
end
Contact.rb
class Contact < ApplicationRecord
belongs_to :branch
belongs_to :division
end
现在用户可以从没有 Division_id 的分支页面创建联系人,并且可以从部门页面创建联系人。
我已经这样定义了我的 routes.rb:
Routes.rb
resources :companies, :shallow => true do
get 'company_page'
resources :branches, :shallow => true do
get 'branch_page'
resources :contacts
end
resources :divisions, :shallow => true do
get 'division_page'
resources :contacts
end
end
因此,如果我从 Branch 或 Division 创建一个联系人,它会转到 contacts#create 方法。
在我的 contacts_controller.rb 中,我有:
def create
@newContact = Contact.new(contact_params)
id = @division = @branch = nil
isBranch = false
if params[:branch_id] != nil
isBranch = true
id = params[:branch_id]
else
isBranch = false
id = params[:division_id]
end
if isBranch
branch = Branch.find(id)
@newContact.branch = branch
@branch = branch
else
division = Division.find(id)
@newContact.division = division
@division = division
end
respond_to do |format|
if @newContact.save
format.js
format.html { render :nothing => true, :notice => 'Contact created successfully!' }
format.json { render json: @newContact, status: :created, location: @newContact }
else
format.html { render action: "new" }
format.json { render json: @newContact, status: :unprocessable_entity }
end
end
end
但我在@newContact.save期间面对ActiveRecord Error。
我确信我在这里做了一些根本上非常错误的事情,Rails 以另一种我不知道的优雅方式处理这些事情。
【问题讨论】:
-
错误是什么?
-
Completed 500 Internal Server Error in 265ms (ActiveRecord: 66.8ms) -
我猜这个错误是因为
Contact有两个属于关联,但你只给它一个。 log/development.log 中的错误是什么? -
是的,你是对的。我想知道如何处理。问题是
@newContact.save is false,因此它会转到respond_to do |format| block的else 块。 -
你可以做
belongs_to :branch, optional: true; belongs_to :division, optional: true
标签: ruby-on-rails ruby activerecord associations model-associations