Rails:设置关联属性在Rails控制台中有效,但在应用程序中无效

时间:2014-07-09 10:45:54

标签: ruby-on-rails mongodb mongoid

我的rails应用程序中有两个模型 - PaletteColor调色板 has_many 颜色。在create操作中,我希望能够在数据库中使用颜色创建新的Palette调色板是在DB中创建的,但未设置颜色关联属性。在这里,我需要帮助。

颜色模型

class Color
  include Mongoid::Document
  field :code,                  :type => String   
  field :image_url,             :type => String

  validates_presence_of :code, :image_url
  validates_uniqueness_of :code

  belongs_to :palette

  class << self
    def add_new(inputs, data = {})
      color = Color.new(inputs)
      color.save!
      color
    end
  end
end

调色板模型

class Palette
  include Mongoid::Document

  field :code,                  :type => String   #P001, P002 etc

  validates_presence_of :code
  validates_uniqueness_of :code

  has_many :colors

  class << self
    def add_new(inputs, data = {})
      new_palette = Palette.new(inputs.except(:colors))
      if inputs[:colors] && inputs[:colors].kind_of?(Array)
        colors = Color.find(inputs[:colors]).to_a
        p colors  # This correctly prints the colors that was  chosen in the form.

        colors.each do |color|
          new_palette.colors << color
        end
      end
      new_palette.save!
      new_palette
    end
  end
end

以下是服务器日志。收到的params是正确的。但是创建的Palette对象为空colors []

  • 我在rails控制台上执行相同的步骤,colors的设置 Palette对象正常工作。不知道我的错误是什么。

服务器日志

Started POST "/palettes" for 127.0.0.1 at 2014-07-09 16:08:53 +0530 Processing by PalettesController#create as HTML

Parameters: {"utf8"=>"✓", "authenticity_token"=>"/kbEyysOq5F5tNp1ciOGpMVjhVxuL6nwPgJHijl1yrI=", "palette"=>{"code"=>"PCODE1", "colors"=>["53bbe83f616e690429210000", "53bbea4f616e690429220000"]}}

MOPED: 127.0.0.1:27017 COMMAND database=admin command={:ismaster=>1} runtime: 0.5990ms

MOPED: 127.0.0.1:27017 QUERY database=predicta_webapp_development collection=colors selector={"_id"=>{"$in"=>[BSON::ObjectId('53bbe83f616e690429210000'), BSON::ObjectId('53bbea4f616e690429220000')]}} flags=[] limit=0 skip=0 batch_size=nil fields=nil runtime: 0.9210ms

[#<Color _id: 53bbe83f616e690429210000, code: "SL001", meta: "Blah", image_url: "blah", other_data: {}, palette_id: nil>, #<Color _id: 53bbea4f616e690429220000, code: "SL002", meta: "blah", image_url: "blah", other_data: {}, palette_id: nil>]

MOPED: 127.0.0.1:27017 QUERY database=predicta_webapp_development collection=palettes selector={"code"=>"PCODE1"} flags=[] limit=-1 skip=0 batch_size=nil fields={:_id=>1} runtime: 0.7580ms

MOPED: 127.0.0.1:27017 INSERT database=predicta_webapp_development collection=palettes documents=[{"_id"=>BSON::ObjectId('53bd1bbd616e690a6f0c0000'), "other_data"=>{}, "code"=>"PCODE1"}] flags=[]

COMMAND database=predicta_webapp_development command={:getlasterror=>1, :w=>1} runtime: 1.2380ms Redirected to http://localhost:3000/

1 个答案:

答案 0 :(得分:0)

尝试与color对象建立关联后保存palette对象。关联只是在颜色对象上设置palette_id,但不会触发保存/更新。