Rails 5 Join Table Создайте форму, которая добавляет новые строки в таблицу соединений - PullRequest
0 голосов
/ 08 октября 2018

Здравствуйте, я создаю базовое приложение для цитирования для работы.

У меня есть предложение, раздел и таблица объединения. Proposal_Sections

Модели

class Proposal < ApplicationRecord
  has_many :proposal_sections
  has_many :sections, through: :proposal_sections
end

class ProposalSection < ActiveRecord::Base
  belongs_to :proposal
  belongs_to :section
end

class Section < ApplicationRecord
  has_many :proposal_sections
  has_many :proposals, through: :proposal_sections
end

Я хочучтобы пользователь мог добавить существующие разделы к предложению на странице показа, поэтому я создал следующую форму.

Форма для предложения / Показать

<%= form_for @proposal do |f| %>
    <%= f.fields_for :proposal_sections do |t| %>
      <%= t.collection_select :section_id, Section.all, :id, :title %>
      <%= t.submit 'Add Section' %>
    <% end %>
  <% end %>

Форма отображается на странице ине создает ошибок, но результаты не сохраняются.

Я получаю это в своей консоли

Started GET "/proposals/1" for 127.0.0.1 at 2018-10-09 06:33:15 +1000
Processing by ProposalsController#show as HTML
  Parameters: {"id"=>"1"}
  Proposal Load (0.4ms)  SELECT  "proposals".* FROM "proposals" WHERE "proposals"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/proposals_controller.rb:75
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ /Users/jeremybray/.rvm/rubies/ruby-2.4.2/lib/ruby/gems/2.4.0/gems/puma-3.12.0/lib/puma/configuration.rb:225
  Rendering proposals/show.html.erb within layouts/application
  User Load (1.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  ↳ app/views/proposals/show.html.erb:17
   (0.6ms)  SELECT COUNT(*) FROM "sections" INNER JOIN "proposal_sections" ON "sections"."id" = "proposal_sections"."section_id" WHERE "proposal_sections"."proposal_id" = $1  [["proposal_id", 1]]
  ↳ app/views/proposals/show.html.erb:23
  Section Load (0.4ms)  SELECT "sections".* FROM "sections"
  ↳ app/views/proposals/show.html.erb:30
  Rendered proposals/show.html.erb within layouts/application (9.7ms)
  Rendered shared/_head.html.erb (90.8ms)
  Announcement Load (0.4ms)  SELECT  "announcements".* FROM "announcements" ORDER BY "announcements"."published_at" DESC LIMIT $1  [["LIMIT", 1]]
  ↳ app/helpers/announcements_helper.rb:3
  Rendered shared/_navbar.html.erb (2.5ms)
  Rendered shared/_notices.html.erb (0.3ms)
  Rendered shared/_footer.html.erb (0.4ms)
Completed 200 OK in 134ms (Views: 123.9ms | ActiveRecord: 3.2ms)

Контроллеры

class ProposalsController < ApplicationController
  before_action :set_proposal, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!
  # GET /proposals
  # GET /proposals.json
  def index
    @proposals = current_user.proposals.all
  end

  # GET /proposals/1
  # GET /proposals/1.json
  def show
  end

  def add
    @proposal = Proposal.find(params[:proposal_id])
    if request.post?
      @section = Section.find(params[:section_id])
      @proposal.proposal_sections << @section
    end
  end

  # GET /proposals/new
  def new
    @proposal = Proposal.new
  end

  # GET /proposals/1/edit
  def edit
  end

  # POST /proposals
  # POST /proposals.json
  def create
    @proposal = current_user.proposals.new(proposal_params)

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

  # PATCH/PUT /proposals/1
  # PATCH/PUT /proposals/1.json
  def update
    respond_to do |format|
      if @proposal.update(proposal_params)
        format.html { redirect_to @proposal, notice: 'Proposal was successfully updated.' }
        format.json { render :show, status: :ok, location: @proposal }
      else
        format.html { render :edit }
        format.json { render json: @proposal.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /proposals/1
  # DELETE /proposals/1.json
  def destroy
    @proposal.destroy
    respond_to do |format|
      format.html { redirect_to proposals_url, notice: 'Proposal was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_proposal
      @proposal = Proposal.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def proposal_params
      params.require(:proposal).permit(:project, :client, :user, proposal_sections: [], section_ids: [])
    end
end

Мои маршруты

require 'sidekiq/web'

Rails.application.routes.draw do
  resources :sections
  resources :proposals do
    match :add, via: [:get, :post]
  end
  namespace :admin do
      resources :users
      resources :announcements
      resources :notifications
      resources :services

      root to: "users#index"
    end
  get '/privacy', to: 'home#privacy'
  get '/terms', to: 'home#terms'
  resources :notifications, only: [:index]
  resources :announcements, only: [:index]
  authenticate :user, lambda { |u| u.admin? } do
    mount Sidekiq::Web => '/sidekiq'
  end

  devise_for :users, controllers: { omniauth_callbacks: "users/omniauth_callbacks" }
  root to: 'home#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Я уверен, что упустил что-то простое, я ценю ваше терпение и помощь

...