记录未保存到has_many中通过关系连接表

时间:2017-05-15 08:34:41

标签: ruby-on-rails ruby

在这个Rails应用程序中,用户编写故事。用户可以创建集合以对其故事进行分组。但是,他们可以发布不属于任何集合的故事。

创建Story时,我希望连接表Story_Collections保存Collection / Story ID对,但它不起作用。任何帮助表示赞赏! :)

这就是我所拥有的

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

在views / stories / new.html.erb

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

在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

创建故事

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

Story和Collection表正确保存,只有连接表没有。这是连接表的模式。

  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

1 个答案:

答案 0 :(得分:0)

您缺少允许参数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