我正在尝试构建一个表来处理某个广告系列的位置和类别,并使用以下模型关联:
class Campaign < ActiveRecord::Base
has_many :campaign_category_metro_bids, dependent: :destroy
has_many :metros, through: :campaign_category_metro_bids
has_many :categories, through: :campaign_category_metro_bids
end
class Metro < ActiveRecord::Base
has_many :campaign_category_metro_bids
has_many :campaigns, through: :campaign_category_metro_bids
has_many :categories, through: :campaign_category_metro_bids
end
class Category < ActiveRecord::Base
has_many :campaign_category_metro_bids
has_many :campaigns, through: :campaign_category_metro_bids
has_many :metros, through: :campaign_category_metro_bids
end
class CampaignCategoryMetroBid < ActiveRecord::Base
belongs_to :campaign
belongs_to :category
belongs_to :metro
end
尝试创建用于选择两个不同城市和类别的广告系列时,其中一个参数的ID的结果为NULL:
广告系列制作代码:
def new
if signed_in?
# create new campaign
@user = User.find(params[:id])
@campaign = @user.campaigns.new
else
redirect_to signin_path
end
end
def create
@campaign = User.find(params["campaign"]["user_id"]).campaigns.build(campaign_params)
if @campaign.save
flash[:success] = "Campaign created!"
redirect_to current_user
else
render 'new'
end
end
已更新 创建广告系列的视图对Category和Metro使用两个单独的collection_select:
<%= f.collection_select :category_ids, Category.all, :id, :display_category, {}, {multiple: true} %>
和
<%= f.collection_select :metro_ids, Metro.all, :id, :full_name, {}, {multiple: true} %>
campaigns_params:
def campaign_params
params.require(:campaign).permit(:name, :campaign_category_metro_bid_id,
:metro_ids => [], :category_ids => [])
end
是否有更好的方法可以在我尝试时创建3表关系?
或者在选择时链接Category
和Metro
模型的方法,以便在制作广告系列时生成的结果如下所示:
答案 0 :(得分:0)
我认为问题可能是您对类别和地铁的多选。您实际上是在尝试将多个foreign_keys用于相同的引用到单行记录中。如果类别ID和城域ID都定义为整数,则需要创建多个记录才能保存。
您需要添加一些逻辑来查看您的选择参数的长度是否为&gt; 1并且基于此,您需要创建并保存新行。逻辑看起来像这样
params[:category_ids].each do |category|
params[:metro_ids].each do |metro|
@user.campaign.create(category_id: category, metro_id:metro) #any other params would go here too
end
end
这实际上会循环遍历多选,为每个组合创建一个新记录。