質問

BookフォームからEditorを作成するための仮想属性を持つModel Bookがあります。 コードは次のようになります。

class Book < ActiveRecord::Base
  has_many :book_under_tags
  has_many :tags, :through => :book_under_tags
  has_one  :editorial
  has_many :written_by
  has_many :authors, :through => :written_by

  def editorial_string
   self.editorial.name unless editorial.nil?
   ""
  end
  def editorial_string=(input)
    self.editorial = Editorial.find_or_create_by_name(input)
  end
end

そして新しいフォーム:

<% form_for(@book,
            :html => { :multipart => true }) do |f| %>
  <%= f.error_messages %>

...
  <p>
    <%= f.label :editorial_string , "Editorial: " %><br />
    <%= f.text_field :editorial_string, :size => 30  %> <span class="eg">Ej. Sudamericana</span>
  </p>
 ...

これにより、フォームデータが検証に合格しなかった場合、フォームが再表示されたときに編集フィールドに送信されたデータを失い、新しいエディターも作成されます。この2つの問題を修正するにはどうすればよいですか?私はルビーがかなり新しく、解決策が見つかりません。

コントローラーの更新:

  def create
    @book = Book.new(params[:book])
    respond_to do |format|
      if @book.save
        flash[:notice] = 'Book was successfully created.'
        format.html { redirect_to(@book) }
        format.xml  { render :xml => @book, :status => :created, :location => @book }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @book.errors, :status => :unprocessable_entity }
      end
    end
  end
役に立ちましたか?

解決

その原因は、Book#editorial_stringメソッドが常に&quot;&quot;を返すことです。次のように簡略化できます:

  def editorial_string
   editorial ? editorial.name : ""
  end

コメントに基づいて更新:

ネストされたフォームをやりたいように聞こえます。 ( api docsのaccepts_nested_attributes_forを参照してください) Rails 2.3。

したがって、Bookクラスを更新する場合

class Book < ActiveRecord::Base
  accepts_nested_attributes_for  :editorial
  ...
end

(editorial_string =、editorial_stringメソッドも削除できるようになりました)

フォームを次のように更新します

...
<% f.fields_for :editorial do |editorial_form| %>
  <%= editorial_form.label :name, 'Editorial:' %>
  <%= editorial_form.text_field :name %>
<% end %>
...

他のヒント

最初の問題は

def editorial_string
  self.editorial.name unless editorial.nil?
  ""
end

常に&quot;&quot;を返しますそれが最後の行だからです。

def editorial_string
  return self.editorial.name if editorial
  ""
end

この問題は修正されます。検証がパスしない理由に関しては、コントローラーで何をしているのかわかりません。どの検証エラーが発生していますか?

このポッドキャストをご覧ください http://railscasts.com/episodes / 167-more-on-virtual-attributes 。 find_or_createをeditorial_string =(input)から移動する必要があると思います  保存後にコールバックするメソッド。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top