0

私は最初の Rails アプリケーションを構築していますが、今まではすべてうまくいきましたが、次のシナリオを見つけました: 1 つのプレゼンテーションには N 回の反復があるはずです。私はRESTを使用していません。そこで、反復を作成するための簡単なフォームを作成しようとしていました。

これらはモデルです:

class Presentation < ActiveRecord::Base
  has_many :iterations
end

class Iteration < ActiveRecord::Base
  belongs_to :presentation
  attr_accessible :presentation_id, :description, :delivery_date, :file
  validates :presentation_id, :presence => {:message => 'is required.'}
end

コントローラーのアクションは次のとおりです。

#Shows Form
def add
  @iteration = Iteration.new
  @presentation = Presentation.find(params[:id])
end

#Saves Form
def save
  @iteration = Iteration.new(params[:iteration])
  @iteration.delivery_date = Time.now
  if @iteration.save
    flash[:notice] = "Saved succesfully!"
  else
    flash[:error] = "Changes were not saved."
  end
  redirect_to root_url
end

これらは HAML のビューになります。

= form_for @iteration, :url => { :action => "save", :method => "post" }, :html => { :multipart => true }  do |f|

- if @iteration.errors.any?
  There were some errors:
  .notice-text.fg-color-white
    %ul.notice
    - for message in @iteration.errors.full_messages
      %li= message
%br

.field
  = f.label :description, "Description"
  = f.text_area :description, :class=>"form-text-area", :rows=>5
.field
  = f.label :file, "Upload File"
  = f.file_field :file
.field
  = hidden_field_tag :presentation_id, @presentation.id
%br
= f.submit "Save"

問題は、save メソッドが保存されないことですが、ビューの @iteration.errors.count の値は 0 です。代わりに、別の投稿で読んだように、次のエラーがスローされます。

検証に失敗しました: プレゼンテーションが必要です。

何が間違っているのかわかりません。以前はビューで「hidden_​​field_tag」の代わりに「f.hidden_​​field」を使用していましたが、他の理由で変更しましたが、その前に同じエラーが発生していたことに注意してください。

4

2 に答える 2

1

あなたのHAML、

hidden_field_tag :presentation_id

する必要があり、

f.hidden_field :presentation_id, :value => @presentation.id
于 2013-03-17T20:15:53.653 に答える
1

持つことができるモデル定義を見ると、

  1. ネストされたリソース: ネストされたリソースのコントローラー パスを参照してください- 未定義のメソッド `<controller>_path'

  2. 仮想属性の使用: これに関する Ryan による非常に便利なレールキャスト -> http://railscasts.com/episodes/16-virtual-attributes-revised

  3. プレゼンテーション ID をセッションに保存します: (これは非常にクリーンな方法ではありません)

コントローラーでは、プレゼンテーション ID が正しく入力されるように、プレゼンテーションの反復をインスタンス化する必要があります。

于 2013-03-17T23:08:12.697 に答える