我有3个型号。用户,简历和语言。用户有一个简历。简历有很多种语言。用户通过其简历有多种语言。当我尝试保存表单时,我收到错误,语言没有用户ID。如何让用户ID通过简历和表格中的语言传递?
CV正在接收用户ID。语言不是。
我正在使用Simple-Form和Cocoon宝石。
= simple_form_for(@cv, url: user_cvs_path) do |f|
= f.simple_fields_for :languages do |language|
has_one :cv, dependent: :destroy
has_many :languages, through: :cv, inverse_of: :user
belongs_to :user
has_many :languages, dependent: :destroy
accepts_nested_attributes_for :languages, allow_destroy: true
belongs_to :user
belongs_to :cv
before_action :set_user
def new
@cv = @user.build_cv
@cv.languages.build
end
def create
@cv = @user.create_cv(cv_params)
respond_to do |format|
if @cv.save
format.html { redirect_to user_cv_url(@user, @cv), notice: 'Cv was successfully created.' }
format.json { render :show, status: :created, location: @cv }
else
format.html { render :new }
format.json { render json: @cv.errors, status: :unprocessable_entity }
end
end
end
def cv_params
params.require(:cv).permit(
:user_id,
:first_name,
:middle_name,
:last_name,
... # lots of params left out for brevity
languages_attributes: [
:id,
:cv_id,
:user_id,
:name,
:read,
:write,
:speak,
:listen,
:_destroy])
end
def set_user
@user = current_user if user_signed_in?
end
答案 0 :(得分:1)
您的语言模型不需要belongs_to :user
。语言属于CV,CV属于User,因此语言和用户之间的关系已经到位。如果您需要访问特定语言的用户,可以编写@language.cv.user
要解决您的问题,只需从语言模型中删除belongs_to:user,从languages_attributes中删除user_id,然后从languages表中删除user_id。