我是新來的鐵軌和我可能會丟失一些非常基本的位置:爲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