gpt4 book ai didi

mysql - 嵌套模型的新建和创建操作不保存 user_id

转载 作者:行者123 更新时间:2023-11-29 13:36:42 26 4
gpt4 key购买 nike

好吧,我有三个模型......用户、集合和设计。

我的模型=

用户模型

 `has_many :collections
has_many :designs, :through => :collections`

集合模型

`belongs_to :user
has_many: designs`

设计模型

`belongs_to :user
belongs_to :collection`

好吧,当我尝试创建一个集合时一切正常。所有参数都保存到数据库中,包括使用 (current_user) 与其关联的 user_id。

当我尝试创建一个设计(属于一个集合)时,我的问题就出现了。当我创建新设计时,未存储 user_id

这是我的新方法和创建方法的设计 Controller

设计 Controller :

`def new
if signed_in? && current_user == @collection.user
@user = current_user
@collection = @user.collections.find(params[:collection_id])
@design = @collection.designs.new
else
flash[:error] = "That's not your collection"
redirect_to root_url
end
end`

'def create
@collection = current_user.collections.find(params[:collection_id])
@design = @collection.designs.new(design_params)

respond_to do |format|
if @design.save
format.html { redirect_to collection_designs_path(@collection), notice: 'Design was successfully created.' }
format.json { redirect_to collection_designs_path(@collection) }
else
format.html { render 'designs/new' }
format.json { render json: @design.errors, status: :unprocessable_entity }
end
end
end`

这是我使用的表单(减去字段)

`<%= form_for [@collection, @design], :html => { :multipart => true, :class => "auth" } do |f| %>
<fields are here>
<% end %>`

为了澄清,我可以提交表单,表单可以工作,并且设计是通过附加的 collection_id 创建的,但不幸的是 user_id 没有与之关联......

最佳答案

您尚未将任何用户对象与设计相关联。试试这个设计 Controller 。在创建操作中,

设计 Controller

def create
@collection = current_user.collections.find(params[:collection_id])
@design = @collection.designs.new(design_params)
@design.user = current_user

respond_to do |format|
if @design.save
format.html { redirect_to collection_designs_path(@collection), notice: 'Design was successfully created.' }
format.json { redirect_to collection_designs_path(@collection) }
else
format.html { render 'designs/new' }
format.json { render json: @design.errors, status: :unprocessable_entity }
end
end
end`

关于mysql - 嵌套模型的新建和创建操作不保存 user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18648948/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com