【问题标题】:Rails has_many :through with collection_select form helperRails has_many :through with collection_select 表单助手
【发布时间】:2015-03-19 11:04:49
【问题描述】:

我在创建将保存我的 has_many 的表单时遇到问题:通过关联。我已经通过发布 json 成功保存了,但是这些表格还对我不起作用。表单提交创建的请求参数将无法正常工作。任何指向我解决方案的帮助都将帮助我避免在这方面浪费更多时间。预先感谢。

已编辑 -- 添加了 forms_for 尝试和创建的在底部无法正常工作的参数 json --

有效的 Json 发布请求参数:

{
    "author": {
        "name": "Author Name",
        "post_authors_attributes": [
          {"post_id":"1"},
          {"post_id":"2"},
          {"post_id":"3"}
        ]
    }
}

Rails 表单生成的参数不保存。

{
    "author": {
        "name": "assd",
        "post_authors_attributes": [
            "",
            "2",
            "3"
        ]
    }
}

...以及相关的代码示例...

作者模型

class Author < ActiveRecord::Base
  has_many :post_authors
  has_many :posts, :through => :post_authors
  accepts_nested_attributes_for :post_authors
end

帖子模型目前只对作者工作有很多帖子,反之不行

class Post < ActiveRecord::Base
end

PostAuthor 模型

class PostAuthor < ActiveRecord::Base
  belongs_to :post
  belongs_to :author
end

作者控制器新建/创建操作

  # GET /authors/new
  def new
    @author = Author.new
    @author.post_authors.build
  end

  # POST /authors
  # POST /authors.json
  def create
    @author = Author.new(params)

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

作者/_form.html.erb

<%= form_for(@author) do |f| %>
  <% if @author.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@author.errors.count, "error") %> prohibited this author from being saved:</h2>

      <ul>
      <% @author.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>

    <%= collection_select(:author, :post_authors_attributes, Post.all, :id, :title,
                                     {include_blank: false, :selected => @author.posts.map(&:id)},
                                     {:multiple => true}) %>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

架构

ActiveRecord::Schema.define(version: 20150120190715) do

  create_table "authors", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "post_authors", force: :cascade do |t|
    t.integer  "post_id"
    t.integer  "author_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "posts", force: :cascade do |t|
    t.string   "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

编辑 -- 添加详细信息 -- 只是为了尽职调查,我也尝试过使用fields_for,但它会产生更混乱的json,不会保存到数据库中。我不知道“0”键是从哪里来的。我坚持这一点,任何帮助将不胜感激。

fields_for

  <div class="field">
    <%= f.fields_for :post_authors, @author.post_authors do |posts_form| %>
        <%= f.label :Posts %><br>
        <%= posts_form.collection_select(:post_id, Post.all, :id, :title,
                                         {include_blank: false, :selected => @author.posts.map(&:id)},
                                         {:multiple => true}) %>

    <% end %>
  </div>

生成的参数 to_json

{
    "author": {
        "name": "test",
        "post_authors_attributes": {
            "0": {
                "post_id": [
                    "",
                    "1",
                    "2",
                    "3"
                ]
            }
        }
    }
}

【问题讨论】:

  • 你能发布你控制器中使用的strong params方法吗?
  • 当然。这是我尝试过的。 def author_params params.require(:author).permit(:name, :post_authors_attributes =&gt; [:post_id]) end
  • 仅供参考,我发布的所有 json 参数都来自实际的 Rails 参数,然后再通过强参数方法发送。我唯一一次看到未经允许的参数问题是在使用“fields_for”(在上面的编辑中添加)时,它抱怨“未经允许的参数:0”,我还看到“未经允许的参数:post_id”。有些东西对我来说没有点击。
  • 可能是因为您缺少:id。试试这个params.require(:author).permit(:id,:name, :post_authors_attributes =&gt; [:id,:post_id])

标签: ruby-on-rails has-many-through collection-select


【解决方案1】:

对于任何遇到同样问题的人,我终于设法让它与以下 collection_select 一起工作:

      <%= f.collection_select(:feature_ids, Feature.all, :id, :name,
                              {include_blank: false, :include_hidden => false, :selected => @property.features.map(&:id)},
                              {:multiple => true}) %>

【讨论】:

    【解决方案2】:

    authors/_form.html.erb:

    <%= fields_for(@author_book) do |ab| %>
      <div class="field">
        <%= ab.label "All Books" %><br>
        <%= collection_select(:books, :id, @all_books, :id, :name, {:selected => @author.books.map(&:id)}, {multiple: true}) %>
      </div>
    <% end %>
    

    authors_controller.rb:

    class AuthorsController < ApplicationController
      before_action :set_author, only: [:show, :edit, :update, :destroy]
    
      # GET /authors
      # GET /authors.json
      def index
        @authors = Author.all
      end
    
      # GET /authors/1
      # GET /authors/1.json
      def show
      end
    
      # GET /authors/new
      def new
        @author = Author.new
        get_books
        respond_to do |format|
        format.html
        format.json { render json: @author }
      end
    
      end
    
      # GET /authors/1/edit
      def edit
        get_books
      end
      # POST /authors
      # POST /authors.json
      def create
    
        @author = Author.new(author_params)
        params[:books][:id].each do |book|
          if !book.empty?
            @author.authorbooks.build(:book_id => book)
          end
        end
    
        #binding.pry
        respond_to do |format|
          if @author.save
    
            format.html { redirect_to @author, notice: 'Author was successfully created.' }
            format.json { render :show, status: :created, location: @author }
          else
            format.html { render :new }
            format.json { render json: @author.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # PATCH/PUT /authors/1
      # PATCH/PUT /authors/1.json
      def update
        #binding.pry
        respond_to do |format|
          if @author.update(author_params)
    
            @author.books = []
            params[:books][:id].each do |book|
              if !book.empty?
                @author.books << Book.find(book)
              end
            end
    
            format.html { redirect_to @author, notice: 'Author was successfully updated.' }
            format.json { render :show, status: :ok, location: @author }
          else
            format.html { render :edit }
            format.json { render json: @author.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # DELETE /authors/1
      # DELETE /authors/1.json
      def destroy
        @author.destroy
        respond_to do |format|
          format.html { redirect_to authors_url, notice: 'Author was successfully destroyed.' }
          format.json { head :no_content }
        end
      end
    
      private
        # Use callbacks to share common setup or constraints between actions.
        def set_author
          @author = Author.find(params[:id])
        end
    
        # Never trust parameters from the scary internet, only allow the white list through.
        def author_params
          params.require(:author).permit(:name,:authorbooks_attributes => [:id,:book_ids => []])
    
        end
    
        def get_books
          @all_books = Book.all
          @author_book = @author.authorbooks.build
        end
    
        # def create_params
        #   params.require(:authorbooks).permit(:author_id,book_id: [])
        # end
    end
    

    【讨论】:

    • 即使我遇到了同样的问题,现在我已经解决了。如果您有任何问题,请在下方评论
    猜你喜欢
    • 2015-11-27
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 2019-03-04
    • 2019-10-29
    相关资源
    最近更新 更多