26

I'm trying to pass the parameter of the current page(id) to the next page so I can create a dependent model entry.

i.e. Projects have bids, bids belong to projects.

So on the show page for a project I added the link

<%= link_to "New Bid", new_bid_path(@project) %>

Which creates and performs the url.... "http://localhost:3000/bids/new.2"

I have

def new
    @bid = Bid.new
    @project =  Project.find(params[:id])
end

in the bids controller but I keep getting the error "Couldn't find Project without an ID"

???

Whats going on, how come I can't pass the id?

ChrisWesAllen
  • 4,935
  • 18
  • 58
  • 83
  • 1
    how do you have your routing setup for this? it seems a little strange that you would have a url that ends with "new.2." if you simply declare resources :bids it also by default doesnt really accept an id paramter, so doing something like new_bid_path(:id) wont work without a little extra configuration – Will Ayd Mar 11 '11 at 02:24
  • Yes thats it.... I changed the link to ..... <%= link_to "New Bid", :controller => "bids", :action => "new", :id => @project %>.... and it works perfectly thanks – ChrisWesAllen Mar 11 '11 at 02:59

2 Answers2

54

If your bids are not nested resource of the project, then you can add project_id as parameter to the path:

<%= link_to "New Bid", new_bid_path(:project => @project.id) %>

def new  
  @bid = Bid.new  
  @project =  Project.find(params[:project])  
end

otherwise:

#routes.rb

map.resources :projects do |project|  
  project.resources :bids
end

<%= link_to "New Bid", new_project_bid_path(@project) %>

def new  
  @project =  Project.find(params[:project_id])    
  @bid = @project.bids.build  
end  
BitOfUniverse
  • 5,903
  • 1
  • 34
  • 38
4

A good approach to this kind of problems, its to see what are you sending with the params. This can be done with debug.

<%= debug params # or any variable%>

With that information you will see (and learn) what kind of params are you sending to a controller.

Gareve
  • 3,372
  • 2
  • 21
  • 23
  • 1
    if you do this make sure to include a "if Rails.env.development?" within the code nugget or else this will appear in production as well – Will Ayd Mar 11 '11 at 02:26
  • I made it "<%= link_to "New Bid", new_bid_path(@project) debug params %>" and the params are being passed...Am I trying to call the parameter in a wrong way in the controller some how? – ChrisWesAllen Mar 11 '11 at 02:29
  • Nope, you need to put the tag (alone) in you 'new' view. – Gareve Mar 11 '11 at 02:33
  • hmm that yields --- !map:ActiveSupport::HashWithIndifferentAccess format: "2" action: new controller: bids – ChrisWesAllen Mar 11 '11 at 02:43