【问题标题】:foreign key not populating in the table on create - rails 3外键未填充在创建表中 - rails 3
【发布时间】:2011-10-06 12:55:33
【问题描述】:

我有两个模型,带有“belongs_to”的“product”和带有“has_many”的“category”。产品有一个外键“category_id”。在 product/_form 表单中,我试图在类别字段中包含一个选择选项,该选项显示类别表中的选项。但是当我单击提交时,category_id 不会填充到产品表中。请帮忙...

product_controller.rb

def create
@product = Product.new(params[:product])

respond_to do |format|
  if @product.save
    format.html { redirect_to([:backend, @product], :notice => 'Product was successfully created.') }
    format.xml  { render :xml => @product, :status => :created, :location => @product }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @product.errors, :status => :unprocessable_entity }
  end
end
end

_form.html.erb

<%= f.label :category %><br />
 <%= f.select :category_id, options_from_collection_for_select(Category.all, :id, :name), :prompt => "Select" %>

models/product.rb

class Product < ActiveRecord::Base

attr_accessible :name, :desc, :price, :is_special

belongs_to :category
end

models/category.rb

class Category < ActiveRecord::Base

attr_accessible :name

has_many :products
end

【问题讨论】:

    标签: ruby-on-rails-3 model associations nested-forms


    【解决方案1】:

    attr_accessible :name, :desc, :price, :is_special对此负责

    您应该将:category_id 添加到此列表中。 当您使用 attr_accessbible 时,所有其他字段都受到保护

    【讨论】:

      猜你喜欢
      • 2021-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 2018-08-06
      • 2012-01-10
      • 1970-01-01
      相关资源
      最近更新 更多