我有两个模型 - 用户和关键字,以及第三个模型关联,用户和关键字通过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