【发布时间】:2019-02-14 11:22:37
【问题描述】:
我有两个模型 - 用户和关键字,第三个模型关联将用户和关键字与 has_many through 关系联系起来。
我在关键字控制器中有一个创建方法,如下所示 -
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
在上面提到的“create”方法中,用户添加关键字后,我会检查关键字表中是否已经存在该关键字,如果不存在,则将关键字保存在关键字表中,然后保存关联表中用户与关键字的关联。
但是,如果关键字表中已经存在关键字(因为它可能已被其他用户添加),并且假设一个新用户正在将这个现有关键字添加到他的列表中,它会给我一个错误 - “你不能在 @keyword.associations.create 行中调用 create ,除非父项已保存”,因为跳过了 @keyword.save (因为该关键字已存在于数据库中)。
我正在使用 Rails 4 和 Ruby 2.0.0
我是 Rails 新手,如果你们能提供任何帮助,我将不胜感激。
更新: 添加关键字模型和关键字控制器的详细信息
型号: 用户模型:
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
【问题讨论】:
标签: ruby-on-rails has-many-through