JayDev
JayDev

Reputation: 11

params in redirect_to not working rails

I am a newbie to rails and I am really stuck on this issue where in my control I want to redirect back to a specific id, but it is giving me a nil value for the url(params[:budget_id]).

I know I can get the params value as I am using it elsewhere to set the value in a view. @budget_id = params[:budget_id] works elsewhere.

My code is as follows, and apologies in advance:

def create

@budget_item = BudgetItem.new(budget_item_params)

respond_to do |format|
  if @budget_item.save
    format.html { redirect_to budget_url(params[:budget_id]) }
    format.json { render :show, status: :created, location: @budget_item }
    else
      format.html { render :new }
      format.json { render json: @budget_item.errors, status: :unprocessable_entity }
    end
  end
end

Just a bit more info: I have a parent budgets/46 when I click on an "add item" button within the budget I now have items/new?budget_id=46. When I save the item I want to return back to the parent budget with id of 46, which I have gotten form the url.

Upvotes: 0

Views: 159

Answers (1)

Marty
Marty

Reputation: 392

Is url a defined method?

Generally, you'd use the route helpers which get generated. From the root of the project do bundle exec rake routes. This will show you call the routes defined and their helpers.

Something like this Prefix Verb URI Pattern Controller#Action api_company GET /api/companies(.:format) api/companies#failure

For for the api call you can use api_company_url(1) for the URL, which would give https://example.com.dev/api/companies/1

Upvotes: 2

Related Questions