gpt4 book ai didi

mysql - Rails 使用连接表将数组参数存储在不同的行中

转载 作者:行者123 更新时间:2023-11-28 23:26:36 25 4
gpt4 key购买 nike

在 rails 4 应用程序中与 has_many :through 关系

city.rb

has_many :business_type_cities
has_many :business_types, :through => :business_type_cities

business_type.rb

has_many :business_type_cities 
has_many :cities, :through => :business_type_cities

businesstypecity.rb

belongs_to :buness_types
belongs_to :cities

business_types_controller.rb

def create
if business_type.save
BusinessTypeCity.create :business_type_id => business_type.id, :city_id => params[:cities]
flash[:notice] = 'Business Type Created Successfully!'
redirect_to admin_business_types_path
else
flash[:error] = business_type.errors.full_messages.join(', ')
end
end

但是这里的city_idarray,我想把business_type_idcity_id存储在一行中,其他city_id 将存储在具有相同 business_type_id 的不同行中。

我得到的响应如下:

"business_type"=>{"name"=>"test", "review_type"=>"review_with_rating"}, "cities"=>["293", "1091", "1200"], "commit"=>"Create Business Type"

谢谢

最佳答案

通常的方法是您在评论中建议的方法。这是我通常做的事情

existing_city_ids = business_type.city_ids
business_type.city_ids = existing_city_ids | params[:cities].map(&:to_i)

首先获取当前业务类型的所有现有城市 ID。然后与新的组合,使用||避免重复,并将params[:cities]映射到int以匹配business_type.city_ids(返回一个数组的 int)

关于mysql - Rails 使用连接表将数组参数存储在不同的行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095158/

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