我是新来的铁轨和我可能会丢失一些非常基本的位置:为belongs_to的众多车型的模型CRUD方法的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
其结果是,如果我创建从任一科或科接触,它去接触#创建方法。
在我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以另一种我不知道的优雅方式处理这些事情。
有什么错误? – Anthony
'在265ms内完成500次内部服务器错误(ActiveRecord:66。8ms)' – user122121
我猜这个错误是因为'联系'有两个属于关联,但你只给它一个。 log/development.log中的错误是什么? – Anthony