1

私は次のモデルを持っています:

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投稿情報を処理し、それを(ほぼ即座に)mongodbに保存できるようにすることです。

入力値をハッシュの正しい場所に配置するためのhamlメソッドは、試行錯誤を繰り返して機能することがわかった方法です。しかし、それは乾燥しているとは感じません、確かに埋め込まれた文書を書くより良い方法がありますか?特にentry[tags_attributes[0 [tag]]]は非常にぎこちなく感じますが、これを書くためのより良い方法はありますか?

また、私のルートでは、タグの文字列を分割して、保存する前に個別の埋め込みドキュメントとしてハッシュ構造に保存します。この情報を解析するのは非常に回りくどい方法だと思います。

これに対処するためのベストプラクティスは何ですか?

4

1 に答える 1

1

Haml

%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}
于 2012-04-27T01:55:43.640 に答える