Rails has_many:通过collection_select表单助手 [英] Rails has_many :through with collection_select form helper

查看:113
本文介绍了Rails has_many:通过collection_select表单助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在创建可保存has_many:with关联的表单时遇到问题.我已经通过发布json成功保存了,但是这些表格对我来说还行不通.表单提交创建的请求参数将无法解决.为我提供解决方案的任何帮助将帮助我避免在此上花费更多的时间.谢谢你.

I'm having issues with creating a form that will save my has_many :through associations. I've successfully saved by posting json, but the forms just won't work for me yet. The request params created by the form submit just won't work out. Any help pointing me to the solution would help me from losing any more time on this. Thanks up front.

已编辑-添加了forms_for尝试和创建的params json在底部效果不佳-

EDITED -- Added forms_for attempt and the created params json that doesn't work as well at the bottom --

Json发布有效的请求参数:

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

使表单生成的参数无法保存.

{
    "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

帖子模型(当前仅在Author上工作的帖子很多,没有相反的帖子)

class Post < ActiveRecord::Base
end

PostAuthor模型

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

Author Controller新建/创建操作

  # 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

authors/_form.html.erb

authors/_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"键从何而来.我坚持下去,任何帮助将不胜感激.

EDIT -- ADDED Details -- Just for due dilligence, I've also tried using a fields_for, but it produces even more messed up json that doesn't save to the database. I have no idea where the "0" key comes from. I'm stuck on this, any help would greatly be appreciated.

fields_for

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的参数

Produced params to_json

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

推荐答案

对于遇到相同问题的任何人,我终于设法将其与以下collection_select一起使用:

For anyone fighting the same kind of issue, I finally managed to get this to work with the following collection_select:

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

这篇关于Rails has_many:通过collection_select表单助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆