Ruby on rails Rails有一个关联设置

Ruby on rails Rails有一个关联设置,ruby-on-rails,associations,belongs-to,has-one,Ruby On Rails,Associations,Belongs To,Has One,嗨,我是rails的新手,几个小时来一直在和这个has_one协会打交道。我有产品和皮肤,当我通过表单创建新产品时,我想使用一个选择框来选择与产品关联的皮肤 在skins表的templates列中保存了haml文件的名称之后,我想在/skin/templates目录中使用haml文件呈现产品 我当前遇到的错误是: undefined method `template' for nil:NilClass 对于控制器中的此行: render "/skins/templates/#{@product

嗨,我是rails的新手,几个小时来一直在和这个has_one协会打交道。我有产品和皮肤,当我通过表单创建新产品时,我想使用一个选择框来选择与产品关联的皮肤

在skins表的templates列中保存了haml文件的名称之后,我想在/skin/templates目录中使用haml文件呈现产品

我当前遇到的错误是:

undefined method `template' for nil:NilClass
对于控制器中的此行:

render "/skins/templates/#{@product.skin.template}"
不过,我也尝试过使用skin_id的其他各种配置,但都没有成功

代码如下:

产品\u控制器.rb 产品表 皮桌
皮肤记录中的产品id为空。。。但看起来你的产品应该属于皮肤

1将皮肤id添加到产品表中,并从皮肤表中删除产品id 2更改产品型号

 class Product < ActiveRecord::Base
      attr_accessible :name, :sku, :skin_id
      belongs_to :skin
      validates_presence_of :skin  #add validation
    end
3皮肤模型

class Skin < ActiveRecord::Base
  attr_accessible  :name, :template
  has_many :products
end

您正在尝试对nil对象使用方法。如果你想避免这种情况,只需使用@product.try:skin.try:template谢谢!这很有效。我唯一的问题是,为什么一个皮肤会有很多产品,而不是一个只有一个皮肤的产品?@greetification product属于一个皮肤,因为它有一个外键引用皮肤id。从你的描述来看,似乎可以有很多产品使用任何一个皮肤,这就是“有很多”的来源。
class Skin < ActiveRecord::Base
  attr_accessible :product, :name, :template
  belongs_to :product
end
= form_for @product do |f|

  - if @product.errors.any?
    #error_explanation
      %h1= "#{pluralize(@product.errors.count, "error")} prohibited this product from being saved:"
      %ul
        - @product.errors.full_messages.each do |msg|
          %li= msg

  .field
    = f.label :name
    = f.text_field :name

  = f.select :skin_id, Skin.all.collect{|t| [t.name, t.id]}

  .actions
    = f.submit 'Save'
id  |     name     |         created_at         |         updated_at         
----+--------------+--------------------------------------------------------
  1 | test         | 2013-03-30 18:01:42.102505 | 2013-03-30 18:01:42.102505
 id |  name   | template |         created_at         |         updated_at         | product_id  
----+---------+----------+----------------------------+----------------------------+------------
  1 | Product | product  | 2013-03-30 20:13:26.374145 | 2013-03-30 20:13:26.374145 |             
 class Product < ActiveRecord::Base
      attr_accessible :name, :sku, :skin_id
      belongs_to :skin
      validates_presence_of :skin  #add validation
    end
class Skin < ActiveRecord::Base
  attr_accessible  :name, :template
  has_many :products
end