简体   繁体   中英

Rails 4 Passing Parameters From One Controller to Another

I have a clients controller and and payments controller. When a client is created I want to automatically redirect to a new payment form and also pass the client id to payments.

In the clients model:

has_many :payments

In the payments model:

belongs_to :client

In clients controller:

def create
@client = Client.new(client_params)

respond_to do |format|
  if @client.save
    format.html { redirect_to new_payment_url (:client_id => @client.id) }
    format.json { render action: 'show', status: :created, location: @client }
  else
    format.html { render action: 'new' }
    format.json { render json: @client.errors, status: :unprocessable_entity }
  end
end

end

In payments controller

  def new
    @payment = Payment.new
    @client = Client.where(:id => params[:client_id])
  end

When I create a client it redirects to the new payments form but the client id does not get passed. When I try to save that payment I get an error saying client can't be blank.

I know that you can't pass an object to another controller without first saving it but my understanding was: i) I'm not trying to pass through the entire client object, just the id and ii) doesn't @client.save save the object to the DB then execute and following lines of code?

I'm a little confused about all of this so any help at all would be much appreciated.

Try changing this line

format.html { redirect_to new_payment_url (:client_id => @client.id) }

to look like this

format.html { redirect_to new_payment_url(:client_id => @client.id) }

You only instantiate a new Client via the line

@client = Client.new(client_params)

By that @client will not have an id until the record is saved.

Since i assume you want to create a record and then further process that data actually persist the record by calling create instead of new .

@client = Client.create(client_params)

Try changing this line:

format.html { redirect_to new_payment_url (:client_id => @client.id) }

to look like this:

format.html { redirect_to new_payment_path(:client_id => @client.id) }

If the above does not work, then pass the 'path' string to redirect_to like these "/payment/new?client_id=#{@client.id}" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM