has_many форма соединения с флажками коллекции, не сохраняющими более одного значения флажка - PullRequest
0 голосов
/ 04 мая 2018

Я работаю над формой для приложения-редактора календаря. У меня есть две вещи, которые очень похожи и не работают.

Работа с 3 моделями: платформы, посты и календари. Это соединительные столы. Платформа <=> Публиковать, Публиковать <=> календари

Post/new & Post/edit form:
    <div class="container">
  <div class="form-field">
    <%= form_for @post do |f| %>
    <%= f.label :title %>
    <%= f.text_field :title, required: true %> <br>
    Title is required.
  </div>

  <div class="form-field">
    <%= f.label :content%>
    <%= f.text_area :content%>
  </div>

  <div class="form-field">
    <%= f.label :link %>
    <%= f.text_field :link %>
  </div>

  <div class="file-field">
    <%= f.label :picture%>
    <%= f.file_field :picture, id: :post_picture%>
  </div>

  <div class="file-field">
    <%= f.label :finalized %>
    <%= f.radio_button :finalized , true%>
    <%= f.label :finalized, "Yes" %>
    <%= f.radio_button :finalized, false %>
    <%= f.label :finalized, "No" %>
  </div>

  <%= f.hidden_field :user_id %> <br>

  <div class="form-field">
    <%= f.fields_for :platform_attributes do |platform| %>
    <%= platform.label :platform, "Social Platforms"%>
    <%= platform.collection_check_boxes :platform_ids, Platform.all, :id, :name %> <br> <br>
  </div>
  <div>
    <h4> Or Create a new platform: </h4>
    <%= platform.label :platform, 'New Platform'%>
    <%= platform.text_field :name%> <br> <br>
  </div>
  <% end %>


  <%= f.submit%>

  <% end %>
</div>

Мой почтовый контроллер обрабатывает проблему с флажками и проблему "расписания сообщений". Это позволит мне запланировать только один календарь и не будет сохранять обновления и добавлять дополнительные календари.

 Posts Controller:
    class PostsController < ApplicationController
      before_action :set_post, only: [:show, :edit, :update, :schedule_post, :destroy]

    def new
        @posts = current_user.posts.select {|p| p.persisted?}
        @post = current_user.posts.build
        @platforms = Platform.all
      end

      def edit
        @calendars = current_user.calendars
        @platforms = Platform.all
      end

      def create
        @post = current_user.posts.build(post_params)
        if @post.save
          redirect_to post_path(@post)
        else
          redirect_to new_post_path
        end
      end

      def update
        @post.update(post_params)
        if @post.save
          redirect_to post_path(@post), notice: 'Your post has been updated.'
        else
          redirect_to edit_post_path(@post)
        end
      end

      def schedule_post
        @calendar_post = CalendarPost.new(calendar_post_params)
        if @calendar_post.save
          binding.pry
          redirect_to post_path(@post)
        else
          render 'show'
        end
      end

      private
      def set_post
        @post = Post.find(params[:id])
      end

      def set_calendars
        @calendars = current_user.calendars
      end

      def post_params
        params.require(:post).permit(:title, :content, :link, :finalized, :picture, :user_id, :platform_attributes => [:platform_ids, :name])
      end

      def calendar_post_params
        params.require(:calendar_post).permit(:post_id, :calendar_id, :date, :time)
      end
    end

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

У меня также есть мой сеттер в моей модели Post.

class Post < ApplicationRecord
  has_many :calendar_posts
  has_many :calendars, through: :calendar_posts
  has_many :platform_posts
  has_many :platforms, through: :platform_posts
  belongs_to :user




 def platform_attributes=(platform_attributes)
        if platform_attributes['platform_ids']
          platform_attributes.platform_ids.each do |id|
            platform = Platform.find(id: id)
            self.platforms << platform
          end
        end
        if platform_attributes['name'] != ""
          platform = Platform.find_or_create_by(name: platform_attributes['name'])
          self.platforms << platform
        end
      end

мысли? почему они не сохраняют более одного календаря или более одной платформы, если они выбирают более одного?

Вот обновленный код ... и больше того, что я знаю об этих изменениях и что происходит.

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

В форме вы можете выбрать флажки или добавить в платформу. Если вы добавляете платформу, она создает ее, но не сохраняет и другие выбранные вами. Если вы перейдете к редактированию сообщения и нажмете «Отправить» с изменениями, страница вообще не загружается и в журнале ничего не происходит. Это просто без дела.

1 Ответ

0 голосов
/ 04 мая 2018
<%= f.fields_for :platform_attributes do |platform| %>

предполагает, что вы создаете одну платформу ... там написано "это поля для этой платформы"

, но platform_ids предназначен для выбора набора платформ ... и, вероятно, должен находиться за пределами секции fields_for (которая должна окружать только поле name).

попробуйте что-то вроде следующего:

<div class="form-field">
    <%= f.label :platform_ids, "Social Platforms"%>
    <%= f.collection_check_boxes :platform_ids, Platform.all, :id, :name %> <br> <br>
  </div>
  <div>
    <%= f.fields_for :platform_attributes do |platform| %>
     <h4> Or Create a new platform: </h4>
      <%= platform.label :name, 'New Platform'%>
      <%= platform.text_field :name%> <br> <br>
    <% end %>
    <%# end fields_for %>
  </div>

Также вам необходимо обновить разрешение / запросить, например,

  def post_params
    params.require(:post).permit(:title, :content, :link, :finalized, :picture, :user_id, :platform_ids, :platform_attributes => [:name])
  end

Примечание: не тестировалось - ошибки оставлены в качестве упражнения для читателя;)

...