Недопустимый параметр: Rails 5.2 - PullRequest
0 голосов
/ 16 января 2020

Я создаю приложение, где пользователи могут публиковать sh там объектов недвижимости. Итак, у меня есть две таблицы, одна из которых называется Свойство , а другая - Amenity (для значков, таких как ванные комнаты, бассейн и т. Д. c.) Я сделал таблицу Amenity отделенной от Таблица свойств, так что я могу использовать ее с другими таблицами, и у меня есть эта ошибка Недопустимый параметр :: gym

Так вот мой код:

property.rb модель

class Property < ApplicationRecord
    belongs_to :owner
    has_many :amenities
    accepts_nested_attributes_for :amenities
end

amenity.rb модель

class Amenity < ApplicationRecord
    belongs_to :property
end

properties_controller.rb

class PropertiesController < ApplicationController
  before_action :set_property, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_owner!

  .
  .
  .

  # POST /properties
  # POST /properties.json
  def create
    @property = current_owner.properties.new(property_params)

    respond_to do |format|
      if @property.save
        format.html { redirect_to @property, notice: 'Tu propiedad ha sido creada!' }
        format.json { render :show, status: :created, location: @property }
      else
        format.html { render :new }
        format.json { render json: @property.errors, status: :unprocessable_entity }
      end
    end
  end

 .
 .
 .

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

    # Never trust parameters from the scary internet, only allow the white list through.
    def property_params
      params.require(:property).permit(:name, :description, :price, amenities_attributes: [:id, :bathroom, :room, :pool, :gym, 
        :kitchen, :terrace, :balcony, :living_room, :garage, :parking_lot, :green_area])
    end
end

таблица миграции объектов

    class CreateAmenities < ActiveRecord::Migration[5.2]
      def change
        create_table :amenities do |t|
          t.integer :bathroom
          t.integer :room
          t.integer :pool 
          t.integer :gym
          t.integer :kitchen
          t.integer :terrace
          t.integer :balcony
          t.integer :living_room
          t.integer :garage
          t.integer :parking_lot
          t.integer :green_areas

          t.references :property
          t.timestamps
        end
        add_index :amenities, [:id, :created_at]
      end
    end

таблица миграции свойств

class CreateProperties < ActiveRecord::Migration[5.2]
  def change
    create_table :properties do |t|
      t.string :name
      t.text :description
      t.integer :price
      t.string :services
      t.string :rules
      t.string :address
      t.float :latitude
      t.float :longitude



      t.references :owner
      t.timestamps
    end
    add_index :properties, [:id, :rfc, :created_at]
  end
end

Консольные журналы

Parameters: {"utf8"=>"✓", "authenticity_token"=>"GjmTFKS3cQRwgrSnTLFOoWQV/gXdTgST0nf7GOs7ZS2i8wneFqzADeTLUo26UKkA5392nrDKGZpVyav4LWpfjw==", "property"=>{"name"=>"Propiedad1", "description"=>"Propiedad1", "price"=>"120000", "gym"=>"1"}, "commit"=>"Create Property"}
  Owner Load (0.3ms)  SELECT  "owners".* FROM "owners" WHERE "owners"."id" = ? ORDER BY "owners"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ /Users/kensanchez/.rvm/gems/ruby-2.5.3/gems/activerecord-5.2.4.1/lib/active_record/log_subscriber.rb:98
Unpermitted parameter: :gym

Что касается меня, то это должно работать нормально, но у меня возникли некоторые проблемы с пониманием. Я буду признателен за вашу помощь, ребята! Спасибо.

РЕДАКТИРОВАТЬ:

Моя веб-форма

<%= form_with(model: property, local: true) do |form| %>
    <% if property.errors.any? %>
        <div id="error_explanation">
            <h2><%= pluralize(property.errors.count, "error") %> prohibited this property from being saved:</h2>

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

    <div class="container">
        <div class="field">
            <%= form.label :name %>
            <%= form.text_field :name %>
        </div>

        .
        .
        .
       <!--Gym attribute from amenities-->
        <div class="field">
            <%= form.label :gym %>
            <%= form.number_field :gym %>
        </div>

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

Ответы [ 2 ]

1 голос
/ 16 января 2020

Это то, что я вижу в ваших журналах консоли output

"property"=>{"name"=>"Propiedad1", "description"=>"Propiedad1", "price"=>"120000", "gym"=>"1"}

Это параметры для свойства и последнего значения is "gym" => "1" , по этой причине вы получаете неразрешенный параметр .

Он должен отображаться в подсказки_атрибутов как

"property"=>{"name"=>"Propiedad1", "description"=>"Propiedad1", "price"=>"120000"}, "amenities_attributes": [{ "gym"=>"1" }] }

1 голос
/ 16 января 2020

Эта часть ваших параметров "property"=>{"name"=>"Propiedad1", "description"=>"Propiedad1", "price"=>"120000", "gym"=>"1"} должна иметь ту же структуру, что и в property_params.

Параметр gym должен быть внутри amenities_attributes.

Like это: "property"=>{"name"=>"Propiedad1", "description"=>"Propiedad1", "price"=>"120000", "amenities_attributes" => [{ "gym"=>"1" }]}.

UPD

Проверьте это https://guides.rubyonrails.org/form_helpers.html#nested -формы

Попробуйте использовать этот кусок кода в виде вида:

<!--Gym attribute from amenities-->
<%= form.fields_for :amenities do |amenities_form| %>
  <div class="field">
    <%= amenities_form.label :gym %>
    <%= amenities_form.number_field :gym %>
  </div>
<% end %>
...