Richlewis
Richlewis

Reputation: 15374

Pass associated model id to another form

I have the following association setup

class Donation < ActiveRecord::Base
  belongs_to :campaign
end

class Campaign < ActiveRecord::Base
has_many :donations
end

in my donation controller i have campaign_id as a strong parameter. Now when creating a donation i would like to have the campaign_id available to save in that form, but better off in the controller somewhere im guessing as less open to being edited. To get from the campaign to the donation form i click a button

<%= link_to 'Donate', new_donation_path, class: 'big-button green' %>

as we are already using

def show
  @campaign = Campaign.find(params[:id])
end

How can i get that id into my donations form?

Thanks

Upvotes: 0

Views: 98

Answers (1)

nthj
nthj

Reputation: 445

It sounds like you're looking for Nested Resources.

Basically, your routes.rb might look something like:

resources :campaigns do resources :donations end

Your controller might look something like:

class DonationsController < ApplicationController
  before_action :find_campaign

  def new
    @donation = @campaign.donations.build
  end

  def create
    @donation = @campaign.donations.create(params[:donation])

    # ... 
  end

protected

  def find_campaign
    @campaign ||= Campaign.find(params[:campaign_id])
  end 
end

And your example link, something like...

<%= link_to 'Donate', new_campaign_donation_path(@campaign), class: 'big-button green' %>

Upvotes: 1

Related Questions