Rails无法在create方法上保存对象信息

时间:2015-03-11 17:58:04

标签: ruby-on-rails-4

我有一个简单的两个模型之间建立了很多关系。 “商品”可以有许多“优惠”,优惠只能有一个商品。我可以创建列表,但是当我创建关联的“优惠”时 - 我的优惠表单中的详细信息不会保存到数据库中。对象本身保存,并包含与之关联的列表ID,但表单中没有任何内容可以通过。

我已粘贴了最相关的代码块,任何建议都会受到赞赏。

提供控制器:     class OffersController< ApplicationController中

def new
@listing = Listing.find(params[:id])
@offer = @listing.offers.build
end

def create
@listing = Listing.find(params[:id])
@offer = @listing.offers.create!(params[offer_params])
if @offer.save
  redirect_to offer_path(:id => @offer.id)
end
end

def show
 @offer = Offer.find(params[:id])
end

def index
end

private
def offer_params
params.require(:offer).permit(:offer_price, :offer_terms, :listing_id,     :offer_expiration)
end

end

与优惠相关的表格

<%= @listing.street_address %> (<%= link_to "Back", listings_path %>)

<%= form_for [@offer, @listing], :url => { :action => :create, :id =>   @listing.id}, html: {multipart: true} do |f| %>
<div class="field">
<%= f.label :offer_price %><br>
<%= f.text_field :offer_price %>
</div>
<div class="field">
<%= f.label :offer_terms %><br>
<%= f.text_area :offer_terms %>
</div>
<div class="field">
<%= f.label :offer_expiration %><br>
<%= f.text_field :offer_expiration %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

最后,当我在表单上点击提交时,开发日志条目。正如您所看到的,它会在params散列中正确地存储商品详细信息(我认为),但是当它将其插入数据库时​​,所有商品字段都不会出现。

Started POST "/offers?id=2" for ::1 at 2015-03-11 13:40:01 -0400
Processing by OffersController#create as HTML
Parameters:    {"utf8"=>"✓","authenticity_token"=>"NldTPDo/s/Jyo8SB0I6/OWYWeN0Ukf9JYQU5nASUDONcMl OQTauG+HWxsfjZ4yJLrvDxVtbUaX2sBD63BMIQtA==", "offer"=>{"offer_price"=>"988888",  "offer_terms"=>"financed", "offer_expiration"=>"Never"}, "commit"=>"Create Offer",  "id"=>"2"}

[1m[35mListing Load (0.2ms)[0m  SELECT  "listings".* FROM "listings" WHERE "listings"."id" = ? LIMIT 1  [["id", 2]]


    [1m [36m(0.1ms)[0m [1mbegin transaction [0m   
    [1m [35mSQL(0.4ms)[0m INSERT INTO“offer”(“listing_id”,“created_at”,“updated_at”)VALUES(?,?,?)[[“listing_id”,2],[“created_at”, “2015-03-11 17:40:01.967717”],[“updated_at”,“2015-03-11 17:40:01.967717”]]

[1m[36m (0.8ms)[0m  [1mcommit transaction[0m

[1m[35m (0.1ms)[0m  begin transaction

[1m[36m (0.0ms)[0m  [1mcommit transaction[0m
Redirected to http://localhost:3000/offers/33
Completed 302 Found in 36ms (ActiveRecord: 2.6ms)

1 个答案:

答案 0 :(得分:0)

在仅def create的{​​{1}}替换params[offer_params]

offer_params

其他

def create @listing = Listing.find(params[:id]) @offer = @listing.offers.build(offer_params) # <- the important change if @offer.save redirect_to offer_path(:id => @offer.id) else flash[:error] = @offer.errors.full_messages render :new end end - &gt; .create!

  • 在您的创建操作中使用.build代替.build.create!过早地调用.create! if语句,导致数据库查询加倍。
  • 此外.save不会让错误无声地失败;这意味着,如果.create!上的验证失败,您的申请将会中断。

渲染:如果保存失败则为新

  • 如果模型保存失败,则重新渲染:新视图以防止丢失:创建模板错误,以显示保存错误(即 - &#34;您的商品必须包含价格&#34;)并为用户提供更正其请求的机会。