简体   繁体   中英

Cannot find bids from post_id

I'm having trouble finding my bids that are linked to specific posts via the index method. I have successfully linked my bids to posts (ie I have a post_id column within my bids table), but cannot seem to 'find' them. I currently get the error 'Couldn't find Bid with 'id'='

Bids controller:

class BidsController < ApplicationController
  def index
    @bid = Bid.find(params[:post_id])
  end
end

View:

<ul>
  <% @bid.each do |bid| %>
    <li>$<%= bid.price.floor %></li>
  <% end %>
</ul>

Models (post and bid):

class Bid < ActiveRecord::Base
   belongs_to :post
end

class Post < ActiveRecord::Base
  has_many :bids
end

Routes:

Rails.application.routes.draw do

  root 'static_pages#home'
  get 'add' => 'posts#new'
  get 'posts' => 'posts#index'
  get '/posts/:id/new_bid' => 'bids#new'
  get '/posts/:id/bids' => 'bids#index'

  resources :posts
  resources :bids

end

Any help is appreciated. Thank you.

In your routes, you have

get '/posts/:id/bids' => 'bids#index'

Therefore, you will have a params[:id] for your controller. Then in your controller, you should use it:

class BidsController < ApplicationController
  def index
    @bids = Post.find(params[:id]).bids
  end
end

You might consider using nested resources in routes:

resources :posts do
  resources :bids
end

Then you will automatically have posts/:post_id/bids and you can use parmas[:post_id] in your controller.

Your index action should be doing used where to find all the bids with a particular post_id.

  def index
    @bid = Bid.where(post_id: params[:post_id])
  end

else you can find the post first and then load the bids from the post like so.

  def index
    @bid = Post.find(params[:post_id]).bids
  end

This error is the result of an empty string sent to Model.find() . You may reproduce this error in rails console ( rails c ) with Bid.find('') .

By the route file you provide, you should use :id instead of :post_id . And because you want all bids that matches the post_id, this should be @bid=Bid.where(post_id: params[: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