简体   繁体   中英

Record not saving to join table in has_many through relationship

In this Rails app, Users write Stories. Users can create Collections to group their Stories. However, they are allowed to publish Stories that don't belong to any Collection.

When creating a Story, I want the join table Story_Collections to save the Collection/Story ID pairs but it isn't working. Any help is appreciated! :)

Here's what I have

collection.rb

class Collection < ActiveRecord::Base

    belongs_to :user
    has_many :story_collections
    has_many :stories, through: :story_collections

end

story.rb

class Story < ActiveRecord::Base

  belongs_to :user
  has_many :story_collections
  has_many :collections, through: :story_collections
  has_many :photos
end

story_collection.rb

class StoryCollection < ActiveRecord::Base

    belongs_to :story
    belongs_to :collection

end

In views/stories/new.html.erb

    <%= f.select :collection_ids, Collection.all.pluck(:name, :id), {}, { multiple: true, class: "selectize" } %>

Creating the collections in collections_controller.rb

class CollectionsController < ApplicationController


  def create
    @collection = current_user.collections.build(collection_params)
    if @collection.save
      render json: @collection
    else
      render json: {errors: @collection.errors.full_messages}
    end
  end

  private

    def collection_params
      params.require(:collection).permit(:name, :description)
    end
end

Creating the stories

class StoriesController < ApplicationController

  def new
    @story = Story.new
    authorize @story
  end

  def create
    @story = current_user.stories.build(story_params)
    authorize @story
  end

  private

  def story_params
    params.require(:story).permit(:title, :description, category_ids: [],
    photos_attributes: [:id, :file_name, :file_name_cache, :_destroy])
  end
end

The Story and Collection tables are saving correctly, only the join table is not. Here's the schema for the join table.

  create_table "story_collections", force: :cascade do |t|
    t.integer  "story_id"
    t.integer  "collection_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

You are missing strong-params permitting the parameter story[collection_ids]

def story_params
  params.require(:story).permit(
    :title,
    :description,
    collection_ids: [], # you need to whitelist this, so the value gets set
    category_ids: [],
    photos_attributes: [
      :id,
      :file_name,
      :file_name_cache,
      :_destroy
    ]
  )
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM