ruby Rails发送强参数并同时更新2个表

vbopmzt1  于 2023-04-11  发布在  Ruby
关注(0)|答案(2)|浏览(114)

我是Rails新手,任何建议,技巧都将不胜感激。
轨道:'4.2.5'
我有如下2个表。Shop(主表)Shop_detail(明细表)2个表之间存在关系。

我想做的事

通过 AJAX 向控制器发送用户输入值。值如,shop_name,item_image,price等。
在控制器中,我想创建如下2个表。Shop(主表)-〉用shop_name创建一个新记录。
Shop_detail(detail table)-〉创建一个新记录,其中包含item_image、price和从Shop(Master table)获得的shop_id。
我想把强参数如下。

def post_master_params <- this is for master table.
    params.permit(:shop_name)
end
def post_detail_params
    params.permit(:item_image, :price)
end

@shop = Shop.new(post_master_params)
@shop.save

@shop_detail = Shop_detail.new(post_detail_params)
@shop_detail.shop_id = @shop.id
@shop_detail.save

结果,我得到了下面的错误。
在83 ms内完成406不可接受(ActiveRecord:0.4ms)ActionController::UnknownFormat(ActionController::UnknownFormat):

zpqajqem

zpqajqem1#

你可以一次完成,但要确保你的主表和子表之间有has_many关系,并确保你的子表有belongs_to到master:

def post_detail_params
    params.permit(:shop_name, shop_details: [:item_image, :price] )
end

post = Shop.build(post_detail_params)
post.save

型号关系:

class Shop < ActiveRecord::Base
    has_many: shop_details
end

class ShopDetail < ActiveRecord::Base
    belongs_to: shop
end
yqhsw0fo

yqhsw0fo2#

对于商店,您应该像这样使用:

post_detail_params.except(:shop_details)

对于ShopDetail表,您应该用途:

post_detail_params[:shop_details]

相关问题