2015-01-21 5 views
0

У меня возникли проблемы с созданием формы, которая сохранит мою has_many: через ассоциации. Я успешно сохранил сообщение json, но формы для меня пока не сработают. Параметры запроса, созданные формой submit, не будут работать. Любая помощь, указывающая мне на решение, помогла бы мне потерять больше времени на это. Спасибо фронту.Rails has_many: through with collection_select form helper

EDITED - Добавлена ​​forms_for попытки и созданного Params JSON, который не работает, а в нижней части -

Json сообщение запроса Params, который работает:

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

Сообщение Модель (В настоящее время работает только на Автор имеет много Сообщения, а не обратные)

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 

EDIT - ADDED Подробности - Просто для надлежащего Dilligence, я также попытался с помощью 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> 

Производимые Params to_json

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

Вы можете разместить 'сильный метод params', который используется в контроллере? – Pavan

+0

Несомненно. Вот что я пробовал. определения функции author_params params.require (автор): .permit (: имя,: post_authors_attributes => [: post_id]) end' – Thomas

+0

FYI, хотя, все, что PARAMS JSON я отправил бы от фактического Rails Params прежде чем они будут отправлены через сильные параметры. Единственный раз, когда я видел непредвиденные проблемы с параметрами, - это использование «fields_for» (добавлено в вышеприведенном редактировании), и он жалуется на «Непроизведенный параметр: 0», и я также видел «Параметр unpermitted: post_id». Что-то просто не нажимает на меня. – Thomas

ответ

3

Для тех, кто борется с такой же вопрос, я, наконец, удалось получить эту работу со следующим collection_select:

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

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 
+0

Даже я был застрял в той же проблеме, теперь я ее решил .. if у вас возникли проблемы с комментарием ниже –

Смежные вопросы