我有兩個模型 - 用戶和關鍵字,以及第三個模型關聯,用戶和關鍵字通過has_many關係連接。通過關係通過has_many保存記錄
我在關鍵字控制器創建方法,該方法如下所示 -
def create
@keyword = Keyword.new(keyword_params)
if Keyword.find_by(content: params[:content]).nil?
@keyword.save
end
@keyword.associations.create(:user_id => current_user.id)
flash[:success] = "Keyword successfully created!"
redirect_to keywords_path
在上面提到的,用戶添加的關鍵詞後,我檢查如果該關鍵字在已經存在的「創造」方法關鍵字表,如果不存在,則將關鍵字保存在關鍵字表中,然後保存關聯表中用戶和關鍵字之間的關聯。
但是,當一個關鍵字已經存在於關鍵字表中(因爲它可能已經被另一個用戶添加了),並且可以說一個新用戶將這個現有關鍵字添加到他的列表中,它給了我一個錯誤 - 「你由於@ keyword.save被跳過(因爲關鍵字已經存在於數據庫中),所以不能調用create,除非父鍵被保存在@ keyword.associations.create行。
我使用我的新到Rails的Rails 4和Ruby 2.0.0
,並希望得到任何幫助你們可以提供。
更新: 添加關鍵字模式和關鍵詞控制器的細節
型號: 用戶模式:
class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
has_many :associations
has_many :keywords, :through => :associations
#name
validates :name, presence: true, length: { maximum: 50 }
end
關鍵字模式:
class Keyword < ActiveRecord::Base
has_many :questions
has_many :associations
has_many :users, :through => :associations
validates :content, presence: true, uniqueness: { case_sensitive: false }
end
關聯模型
class Association < ActiveRecord::Base
belongs_to :keyword
belongs_to :user
validates :user_id, :uniqueness => { :scope => :keyword_id }
end
關鍵詞控制器:
class KeywordsController < ApplicationController
before_action :signed_in_user, only: [:index, :edit, :update, :destroy]
def index
@keywords = current_user.keywords.to_a
end
def new
@keyword = Keyword.new
end
def create
@keyword = Keyword.find_by(content: params[:content])
if @keyword.nil?
@keyword = Keyword.create(keyword_params)
end
@keyword.associations.create(:user_id => current_user.id)
flash[:success] = "Keyword successfully created!"
redirect_to keywords_path
end
def destroy
end
private
def keyword_params
params.require(:keyword).permit(:content)
end
end
感謝Vitaliy爲您的迅速反應。不幸的是,你提出的修改給出了同樣的錯誤 - 「你不能調用創建,除非父母被保存」 – amey1908
它可能是因爲父母有一些驗證錯誤,這將有助於如果你插入關鍵字類的內容 –
您好Vitaliy,我添加代碼爲關鍵字模型和控制器在我原來的問題。如果我的驗證有任何問題,請告訴我。謝謝你的幫助。 – amey1908