2009-03-18 1 views
0

記事を作成するために繰り返される自動完成(Pat Shaughnessyによって修正)された複雑なフォーム(railscastなど)を作成しようとしています。多くの著者(has-many:through)と一緒に。私は記事を保存するときに常に新しい著者を作成したいと思っている限り、それを働かせています。関連する著者レコードが存在しないときにのみ作成されるようにするにはどうしたらいいですか?RailsとActiveRecord:たくさんの子にfind-or-createを使って親オブジェクトを保存する

親オブジェクトでこの結果を得るためにfind-or-createを使うことができますが、記事のために@ article.saveが呼び出されたときに保存されている関連オブジェクトには、このオブジェクトが必要です。 articles.rb

before_save :remove_blank_authors 
after_update :save_authors 

def remove_blank_authors 
    authors.delete authors.select{ |author| author.fullname.blank?} 
    end 


def new_author_attributes=(author_attributes) 
    author_attributes.each do |attributes| 
     authors.build(attributes) 
    end 
    end 

def existing_author_attributes=(author_attributes) 
    authors.reject(&:new_record?).each do |author| 
     attributes = author_attributes[author.id.to_s] 
     if attributes 
     author.attributes = attributes 
     else 
     author.delete(author) 
     end 
    end 
    end 

    def save_authors 
    authors.each do |author| 
     author.save(false) 
    end 
    end 

と私の見解の一部の著者で

<div class="author"> 
    <% fields_for_author author do |f| %> 

    <%= error_messages_for :author, :object => author %> 
    <%= f.label :fullname, "Author Fullname:" %> 
    <%= f.text_field_with_auto_complete :author, :fullname, {}, {:method => :get } %> 


    <%= link_to_function "remove", "$(this).up('.author').remove()" %> 

    <% end %> 
</div> 

私はRailsの2.2.2を使用しています。

問題は、どこで検索または作成を使用できるかわかりません。著者の属性が作成されている時点で、new_author_attributes - 私は検索するものがありません。それは私が考える空のオブジェクトを事前に構築するだけです。そして、著者が保存されている時点で、それらはすでに新しいオブジェクトです。または私は間違っていますか?

+0

のようなあなたのビューとモデルのコードを見て何? –

+0

ここの例のようなボイラープレートの標準的なものです:http://patshaughnessy.net/2009/1/30/sample-app-for-auto-complete-on-a-complex-form – srboisvert

答えて

2

それはあなたが使用しているが、あなたが行うことができるはずのRailsのバージョンによって異なります。

@article.authors.find_or_create_by_article_id(@author) 

または

@author.articles.find_or_create_by_author_id(@article) 

その後、Railsはあなたのための詳細を入力、「すべきです」..

find_or_createを使用するには、それを評価するための条件が必要です。その条件(by_author_id部分)は、Articleモデルの任意の列に変更できます。

これは大会の一つでは、Railsは私があまりにも多くの情報を見つけることができませんでしたどの含まれていることを特徴とするので、これは申し訳ありませんが、道オフの場合;)

関連する問題