我的rails应用程序中有两个模型 - Palette
和Color
。 调色板 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 []
。
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/
答案 0 :(得分:0)
尝试与color
对象建立关联后保存palette
对象。关联只是在颜色对象上设置palette_id
,但不会触发保存/更新。