collection_select不会将value_id提交到数据库

时间:2011-10-07 23:38:55

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

<%= collection_select(:category, :category_id, Category.all, :id, :category_name ,:prompt=>"category") %>

不会在deal表中插入category_id。即使在参数中你可以看到category_id在那里,但它没有传递到交易数据库表。这是代码的其余部分。任何帮助将不胜感激。谢谢你

   <%= form_for @deal ,:url=>{:action =>"create"} do |c|%>

    <%= c.text_field :item_name %><br/>
    <%=c.fields_for :stores do |s| %>
    <%=s.text_field :store_name %>
   <%end%>
   <%=c.fields_for :category  do |d| %>
   <%= collection_select(:category, :category_id, Category.all, :id, :category_name ,:prompt=>"category") %>

  <%end%>
  <%= c.submit "post"%>

   <%end%>

模型

    class Deal < ActiveRecord::Base
belongs_to :category
    accepts_nested_attributes_for :category 
    end

    class Category < ActiveRecord::Base
has_many :deals
    end

在日志中

    Parameters: {"utf8"=>"✓",    "authenticity_token"=>"oO5AtFX4HUYAhcP15y/dFzn3kjVDmweykQPqgDDuupQ=", "deal"=> {"item_name"=>"grapes", "stores_attributes"=>{"0"=>{"store_name"=>"winco"}}},  "category_id"=>"2", "commit"=>"post"}
    City Load (0.1ms)  SELECT "cities".* FROM "cities" WHERE "cities"."id" = ? LIMIT  1  [["id", 2]]
    SQL (1.5ms)  INSERT INTO "deals" ("brand", "category_id", "city_id",  "created_at", "item_name", "price", "size", "stars", "updated_at") VALUES (?, ?, ?, ?, ?,  ?, ?, ?, ?)  [["brand", nil], ["category_id", nil], ["city_id", 2], ["created_at", Fri, 07  Oct 2011 23:16:45 UTC +00:00], ["item_name", "grapes"], ["price", nil], ["size", nil],  ["stars", nil], ["updated_at", Fri, 07 Oct 2011 23:16:45 UTC +00:00]]
     SQL (0.5ms)  INSERT INTO "stores" ("address", "created_at", "store_name",  "updated_at") VALUES (?, ?, ?, ?)  [["address", nil], ["created_at", Fri, 07 Oct 2011  23:16:45 UTC +00:00], ["store_name", "winco"], ["updated_at", Fri, 07 Oct 2011 23:16:45 UTC +00:00]]
    SQL (0.9ms)  INSERT INTO "store_deals" ("address", "created_at", "deal_id",  "store_id", "store_name", "updated_at") VALUES (?, ?, ?, ?, ?, ?)  [["address", nil],   ["created_at", Fri, 07 Oct 2011 23:16:45 UTC +00:00], ["deal_id", 4], ["store_id", 4], ["store_name", nil], ["updated_at", Fri, 07 Oct 2011 23:16:45 UTC +00:00]]

3 个答案:

答案 0 :(得分:2)

尝试使用:

<%= c.collection_select(:category_id, Category.all, :id, :name ,:prompt=>"category")%>
or
<%= c.collection_select(:Category_id, Category.all, :id, :name ,:prompt=>"category")%>
or
<%= c.select :category_id, Category.all.collect { |v| [ v.name, v.id ] } %>

没有

        <%=c.fields_for :category  do |d| %>

由于交易属于类别,因此您将不需要交易模型中的category_id或Category_id字段

accepts_nested_attributes_for :category 

除非您尝试在交易的同时创建新类别。

答案 1 :(得分:1)

看看params。 category_id在交易哈希之外(而item_name和stores_attributes在里面)。

您可能需要<%= c.collection_select ... %>

摆脱类别选择周围的fields_for - 没有理由。 category_id是交易的属性,而不是类别。

答案 2 :(得分:0)

最后这个工作

<%= c.collection_select( :category_id, Category.all ,:id,:category_name,:prompt=>"category") %>