我正试图建立一个has_many低谷关系,我是这个
的新手#models/partner.rb
class Partner < ActiveRecord::Base
has_many :cards_partners
has_many :cards, through: :cards_partners
#models/card.rb
class Card < ActiveRecord::Base
has_many :cards_partners
has_many :partners, through: :cards_partners
#models/cards_partner.rb
class CardsPartner < ActiveRecord::Base
belongs_to :card
belongs_to :partner
我指定了控制器
#controllers/cards_controller.rb
before_action :set_card, only: [:show, :edit, :update, :destroy]
def show
@user = @card.user
@partners = @card.partners.order(lastname: :desc)
@partner = @card.partners.new #because I have a modal to create new Partner too
#address is in a polymorphic table. I have to refactor the if-else
if @card.address.street.blank? && @card.address.city.blank?
@address = @user.address
else
@address = @card.address
end
end
def create
@card = current_user.cards.new(card_params)
respond_to do |format|
if @card.save
format.html { redirect_to @card, notice: 'Card was successfully created.' }
format.json { render :show, status: :created, location: @card }
else
format.html { render :new }
format.json { render json: @card.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @card.update(card_params)
format.html { redirect_to @card, notice: 'Card was successfully updated.' }
format.json { render :show, status: :ok, location: @card }
else
format.html { render :edit }
format.json { render json: @card.errors, status: :unprocessable_entity }
end
end
end
private
def set_card
@card = Card.find(params[:id])
end
def card_params
params.require(:card).permit(partner_ids: [])
end
#controllers/partners_controller.rb
def partner_params
params.require(:partner).permit(card_ids: [])
end
我的联接表cards_partners已正确设置。
总结逻辑,用户可以创建卡片并将合作伙伴添加到此卡片。 我在卡片和合作伙伴之间设置了一个has_many,因为我希望用户能够将已创建的合作伙伴分配给多个卡片。
我在cards#show
视图中有一个显示所有合作伙伴的部分内容,以及一个向该卡添加新内容的链接。
我在我的@partners
操作中定义了card#show
(由于未指定连接,因此不确定):
@partners = @card.partners.order(lastname: :desc)
我无法确定如何指定卡片,然后使用链接card#show
从new_partner_path
视图创建新合作伙伴。
任何帮助都会非常感激。 非常感谢你