【问题标题】:Persisting mongoid parent document and embedded documents from Haml on Sinatra在 Sinatra 上持久化来自 Haml 的 mongoid 父文档和嵌入文档
【发布时间】:2012-04-27 10:04:48
【问题描述】:

我有以下型号:

class Entry
  include Mongoid::Document
  field :title, type: String
  field :description, type: String
  field :made, type: Date
  embeds_many :images
  embeds_many :videos
  embeds_many :files
  embeds_many :tags
  accepts_nested_attributes_for :images, :videos, :files, :tags
  validates_presence_of :title, :description, :tags
  validates_uniqueness_of :title, :description
end

class Tag
  include Mongoid::Document
  field :tag, type: String
  embedded_in :entry
  embedded_in :note
end

发布路线如下所示:

post '/portfolio/new' do
  a = (params[:entry])
  a['tags_attributes']['0']['tag'].downcase.split(", ").each_with_index{|value, index| a['tags_attributes'][index.to_s] = {"tag" => value} }
  b = Entry.new(a)
  b.safely.save!
  redirect "portfolio/show/#{b._id}"
end

我的haml输入看起来像:

%label{:for => "tags"} Tags:
%input{:name => "entry[tags_attributes[0[tag]]]"}

我是 Ruby/Sinatra/Mongoid 的新手,所以我仍在尝试弄清楚如何正确访问文档属性。

我要做的是处理http post信息并能够(几乎立即)将其保存到mongodb。

将输入值放置在哈希上正确位置的 haml 方法是我发现的一种通过反复试验来工作的方法。但是感觉不DRY,肯定有更好的方法来编写嵌入文档吗?特别是 entry[tags_attributes[0[tag]]] 感觉很尴尬,有没有更好的写法?

也在我的路线中,为了打破我拥有的标签字符串并将其作为单独的嵌入文档存储回哈希结构,然后再保存。我觉得这是一种非常迂回的方式来解析这些信息。

处理此问题的最佳做法是什么?

【问题讨论】:

    标签: sinatra mongoid haml


    【解决方案1】:

    哈姆

    %input{name: 'entry[tags_attributes][][tag]', value: t.tag}
    

    简单路线

    post '/portofolio/new' do
      Entry.new(params[:entry])
      ...
    end
    

    注意编辑/放置不要忘记嵌入的 id

    %input{type: 'hidden', name: 'entry[tags_attributes][][id]', value: t.id}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-20
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-14
      相关资源
      最近更新 更多