1

Ryan Bate のエピソード #285 の最初の部分をフォローしています。なぜ機能しないのかわかりません。コードは次のとおりです。

モデル:

class Comic < ActiveRecord::Base
    has_many :comics_genres
    has_many :genres, through: :comics_genres
end

class ComicsGenre < ActiveRecord::Base
    belongs_to :genre
    belongs_to :comic
end

class Genre < ActiveRecord::Base
    has_many :comic_genres
    has_many :comics, through: :comics_genre
end

新しいコミックを作成するためのフォーム:

  <%= form_for ([@user, @comic]) do |f| %>
    <div><%= f.collection_select :genre_ids, Genre.order(:genre), :id, :genre, {}, {multiple: true} %></div>

      <%= f.submit class: "btn btn-primary" %>
  <% end %>

コミックコントローラー:

def create
    @user = current_user
    @comic = @user.comics.new(comic_params)

    respond_to do |format|
      if @comic.save
        format.html { redirect_to @comic, notice: 'Comic was successfully created.' }
        format.json { render action: 'show', status: :created, location: @comic }
      else
        format.html { render action: 'new' }
        format.json { render json: @comic.errors, status: :unprocessable_entity }
      end
    end
  end

def comic_params
      params.require(:comic).permit(:id, :title, :synopsis,
        comic_pages_attributes: [:comic_page_image],
        comics_genres_attributes: [:genre_id, :comic_id])
    end

コンソールでは、次のようなレコードを取得します。

問題は、genre_id が nil であることですが、正しい値を渡す方法がわかりません。

どうもありがとう!

4

1 に答える 1

1

私はそれを考え出した。パラメータを提供してくれた MrYoshi に感謝します。フォームは、変数 @genre_ids に設定したジャンル ID の配列を提供します。コミックが保存された後、その配列を繰り返し処理し、各ジャンル ID をコミック ID と共に保存して、コミックとジャンルのコネクタである comics_genres テーブルのレコードを作成します。

紛らわしい部分は、保存後にコミック ID のみを生成するため、コミックが保存されるまで ComicsGenre インスタンスを保存できないことです。

これが最善の方法ではない場合はお知らせください。もっとエレガントな方法があると確信しています。

def create
    @user = current_user
    @comic = @user.comics.new(comic_params)
    @genre_ids = params[:comic][:genre_ids]

    respond_to do |format|
      if @comic.save

        @genre_ids.each do |genre_id|
          ComicsGenre.create(:comic_id => @comic.id, :genre_id => genre_id)
        end

        format.html { redirect_to @comic, notice: 'Comic was successfully created.' }
        format.json { render action: 'show', status: :created, location: @comic }
      else
        format.html { render action: 'new' }
        format.json { render json: @comic.errors, status: :unprocessable_entity }
      end
    end
  end
于 2014-01-29T20:19:48.640 に答える