作家、作品、フレーズを投稿するフォームがあり、ユーザーがフォームにそれらを投稿する際、
すでにその作家が存在する場合、
・その作家を新規作成せずに、その作品だけを新規作成。
・このとき、もし作品も存在していたら、作品を新規作成せずに、そのフレーズのみを新規作成。
以上のことがしたいのですが、
現状、
①既存の作家に新規の作品をひもづける。
②既存の作家の、既存の作品に新規のフレーズをひもづける。
というところまではできているのですが、
②をする際に、新規に、既存の名前と同じ作品が登録されてしまいます。
これを解決するにはどうしたらよいでしょうか?
以下に、該当する箇所のコードを記載いたします。
class AuthorsController < ApplicationController def new @author = Author.new @writing = @author.writings.build @word = @writing.words.build(author_id: @author.id) end def create @author = Author.find_or_initialize_by(name: params[:author][:name]) @author.update_attributes(author_params) end private def author_params params.require(:author).permit(:id, :name, writings_attributes: [:id, :title, words_attributes: [:id, :content, :author_id]]) end
作家、作品、フレーズのモデル
class Author < ActiveRecord::Base has_many :writings has_many :words, through: :writings accepts_nested_attributes_for :writings class Writing < ActiveRecord::Base belongs_to :author, :autosave => true has_many :words accepts_nested_attributes_for :words def autosave_associated_records_for_author if new_author = Author.find_by(name: author.name) self.author = new_author else self.author.save! end end class Word < ActiveRecord::Base belongs_to :writing, :autosave => true has_one :author, through: :writing def autosave_associated_records_for_writing if new_writing = Author.find_by(name: author.name).writings.find_by(title: writing.title) self.writing = new_writing else self.writing.save! end end end
よろしくお願いいたします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。