Rails 发送强参数并一次更新 2 个表

问题描述 投票:0回答:2

我是 Rails 的新手,任何建议和技巧都将不胜感激。

轨道:'4.2.5'

我有如下两张桌子。 店铺(主桌) Shop_detail(明细表) 2个表之间有关系。

我想做什么

通过 AJAX 将用户输入值发送到控制器。 值如商店名称、商品图片、价格等。

在控制器中,我想创建如下两个表。 商店(主表)-> 用商店名称创建一条新记录。

Shop_detail(明细表)-> 使用从 Shop(主表)获得的 item_image、price 和 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

结果,我得到了下面的错误。

完成 406 Not Acceptable in 83ms (ActiveRecord: 0.4ms) ActionController::UnknownFormat (ActionController::UnknownFormat):

ruby-on-rails ruby strong-parameters
2个回答
1
投票

您可以一次完成,但要确保您在主表和子表之间具有has_many关系,并确保您的子表具有belongs_to以掌握:

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

0
投票

对于 Shop 你应该这样使用:

post_detail_params.except(:shop_details)

对于

ShopDetail 
表,您应该使用:

post_detail_params[:shop_details]
© www.soinside.com 2019 - 2024. All rights reserved.