我无法将我的出价与帖子相关联。我在出价表中创建了post_id
列(通过添加资源:迁移中的帖子)。
我希望能够转到/ posts /:id / new_bid来创建新的出价 那个帖子。目前,我可以通过转到创建新的出价 / posts / 2 / new_bid(例如),但它仍然说'post_id:nil'in 数据库。
路线
root 'static_pages#home'
get 'add' => 'posts#new'
get 'posts' => 'posts#index'
get '/posts/:id/new_bid' => 'bids#new'
resources :posts
resources :bids
出价控制器
class BidsController < ApplicationController
def new
@bid = Bid.new
@post = Post.find(params[:id])
end
def show
@bid = bids.find(params[:id])
end
def index
@bid = bids.all
end
def create
@bid = Bid.new(bid_params)
@post = Post.find(params[:post_id])
if @bid.save
redirect_to root_path
flash[:notice] = 'Bid received!'
else
render 'new'
end
end
def bid_params
params.require(:bid).permit(:price, :company_name, :company_street, :company_city,
:company_zip, :company_phone, :company_email, :post_id)
end
end
出价模式
class Bid < ActiveRecord::Base
belongs_to :post
end
发布模型
class Post < ActiveRecord::Base
has_many :bids
end
模式
ActiveRecord::Schema.define(version: 20150704152313) do
create_table "bids", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.decimal "price"
t.integer "post_id"
end
add_index "bids", ["post_id"], name: "index_bids_on_post_id"
create_table "posts", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "fromstreet"
t.string "fromcity"
end
end
出价:
<%= form_for(@bid) do |f| %>
<div style='float: left; width: 50%;'>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= f.label "Price" %>
<%= f.text_field :price, class: "form-control" %>
<br></br>
<%= f.submit "Submit bid", class: "btn btn-primary" %>
</div>
</div>
</div>
<% end %>
有人可以帮忙吗?
当我将验证测试添加到我的出价模型时,例如:
validates :price, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :company_email, presence: true,
format: { with: VALID_EMAIL_REGEX}
当我输入违反其中一项验证测试的出价时,我收到以下错误:
undefined method `id' for nil:NilClass
和行:
<%= f.hidden_field :post_id, :value => @post.id %>
以红色突出显示。
答案 0 :(得分:0)
尝试使用表单中的hidden_field
。
<%= f.hidden_field :post_id, :value => @post.id %>