Foreign Key in Ruby on Rails 5

1

Good morning, I'm a few days with a problem using Rails5, I can not insert foreign key.

Models:

class Sushi < ApplicationRecord
    belongs_to :tipo_sushi
end

class TipoSushi < ApplicationRecord
    has_many :sushi
end

Migration:

class CreateSushis < ActiveRecord::Migration[5.0]
  def change
    create_table :sushis do |t|
      t.string :name
      t.float :value
      t.integer :tipo_sushi_id
      t.timestamps
    end
    add_index :sushis, :tipo_sushi_id
  end
end

class CreateTipoSushis < ActiveRecord::Migration[5.0]
  def change
    create_table :tipo_sushis do |t|
      t.string :name
      t.string :description

      t.timestamps
    end
  end
end

Main View:

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

  <div class="field">
    <%= f.label :value %>
    <%= f.text_field :value %>
  </div>

  <div>
  <%= f.label :Tipo_Sushi%>
  <%= f.select(:tipo_sushi_id, TipoSushi.all.collect { |c| [ c.name, c.id ] }) %>
  </div>

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

Explaining, I register a type of sushi, then when I register the Sushi, I define the name, value and type, in the type a list of the types registered before, until it is working, I need in the form to submit the ID of the type sushi, but it gives error, as below.

ActiveRecord::SchemaMigration Load (0.3ms)  SELECT 'schema_migrations'.* FROM 'schema_migrations'
Processing by SushisController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"U82zJsuqvkVLeiRw97Ma01yzSHJ4EuDBJLJYsZvOT0tv2c030cNN0xhaWuxMudjopJmtASnnTrTMZiRiC0ZCzg==", "sushi"=>{"name"=>"Tipo1", "value"=>"30", "tipo_sushi_id"=>"1"}, "commit"=>"Create Sushi"}
Unpermitted parameter: tipo_sushi_id
   (0.2ms)  BEGIN
   (0.2ms)  ROLLBACK
    
asked by anonymous 11.07.2016 / 21:09

1 answer

0

Try to modify your controller to stay this way.

def create
    @sushi = Sushi.new(sushi_params)
    if @sushi.save
        # Sucesso.
    else
        render 'new'
    end
end

private

    def sushi_params
        params.require(:sushi).permit(:name, :value, :tipo_sushi_id)
    end

It is a replace for the attr_accessible of the old rails that has not been used since version 4, called Strong Params .

    
12.07.2016 / 03:43