【发布时间】:2014-12-01 00:47:10
【问题描述】:
我在我的两个模型中设置了 has_many belongs_to 关系,并按照 Ryan Bates 的截屏视频了解如何设置控制器。当我提交表单以创建新对象时,嵌套对象由于某种原因没有保存。这是我的模型:
class Auction < ActiveRecord::Base
has_many :bids, dependent: :destroy
end
class Bid < ActiveRecord::Base
belongs_to :auction
belongs_to :user
default_scope -> { order(created_at: :desc) }
validates :user_id, presence: true
validates :auction_id, presence: true
end
还有我的嵌套对象控制器:
class BidsController < ApplicationController
def index
@auction = Auction.find(params[:auction_id])
@bids = @auction.bids
end
def new
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.build
end
def create
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.create(params[:bid])
@bid.save
if @bid.save
flash[:success] = "Bid has been successfully placed."
else
@bid.errors
render 'new'
end
end
def destroy
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.find
@bid.destroy
flash[:notice] = "Successfully destroyed Bid."
redirect_to auction_url(@bid.article_id)
end
end
我的表格:
<h1>Create a New Bid</h1>
<%= form_for ([@auction, @bid]) do |f|%>
<p>
<%= f.submit %>
</p>
<%end%>
和我的终端输出:
Started POST "/auctions/1/bids" for 127.0.0.1 at 2014-11-30 17:59:13 -0600
Processing by BidsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dkZBcab1rgZjtJGF3LAJ//exK6liglZ0Fy4mg7HWEt0=", "commit"=>"Create Bid", "auction_id"=>"1"}
Auction Load (0.1ms) SELECT "auctions".* FROM "auctions" WHERE "auctions"."id" = ? LIMIT 1 [["id", 1]]
(0.0ms) begin transaction
(0.0ms) commit transaction
(0.0ms) begin transaction
(0.0ms) rollback transaction
(0.0ms) begin transaction
(0.0ms) rollback transaction
感谢您的帮助。
【问题讨论】:
标签: ruby-on-rails