Antonin Mrchd Antonin Mrchd - 1 year ago 69
Ruby Question

ActiveRecord Couldn't find Travel with 'id'=

I search a solution on stackoverflow but there are different issues each time, so I decided to ask the question.
On my application, I have Travel, which has many posts. One user can create many travels, with many posts on one travel.
But when I try to create a post, I have this error :

ActiveRecord::RecordNotFound in PostsController#create
Couldn't find Travel with 'id'=

I don't understand why, so if someone could help me ..
Here is my Posts_controller.rb (create action):

def create
@travel = Travel.find(params[:id])
@post =
@post.user = current_user
flash[:success] = "Your post is published"
redirect_to user_path(current_user)
render 'new'

Here is my the models :

class Post < ActiveRecord::Base
belongs_to :user
belongs_to :travel

geocoded_by :country
after_validation :geocode

class Travel < ApplicationRecord
has_many :posts
belongs_to :user

My routes :

# Travel
resources :travels, :shallow => true do
# Posts
resources :posts

And a ligne for form :

<%= form_for(@post, :html => {class: "form-horizontal", role: "form"}, :url => travel_posts_path(@travel)) do |f| %>
<div class="form-group">
<%= f.text_field :travel_id, placeholder: %>

Dbz Dbz
Answer Source

params[:id] will give you the post's id, and you're using it to find a travel. This could potentially not error and give you the wrong travel, but that's not what you're looking for. You specified travel_id in your form, so what you are looking for is params[:travel_id].

In the future you may want to use the debugger right at the top of the controller function and puts the params object to see what's inside. This will give you insight to if you're calling the wrong keys and what the structure looks like as things get complicated.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download