我試圖建立一個表來處理雙方的位置和類別一定的活動已被設置爲以下模型協會:Rails的ActiveRecord的:三表的has_many通過:協會
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
當試圖創建選擇兩個不同的城市和類別的結果的活動是空的paramters之一當ID:
建立廣告活動代號:
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
修訂 視圖創建活動採用兩個獨立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
機型在選擇鏈接:
你可以從你的控制器中添加廣告系列創建代碼的方向? – Eric 2014-09-23 01:23:41
@Eric你需要其他信息嗎? – Sauron 2014-09-23 01:40:33
是的,你的campaign_params方法:) – Eric 2014-09-23 05:06:32