Foreign Key on Ruby on Rails 5

Asked

Viewed 232 times

1

Good morning, I’m a few days with a problem using Rails5, I can’t 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, the type appears a list of types registered previously, until then working, I need in the form submit the ID type sushi, but 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
  • Version 5 of Rails is not in beta?

  • From what I saw on the site June 30 ceased to be (if etendi correct)

1 answer

0

Try modifying your controller to look like this.

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 old Rails attr_accessible that is no longer used since version 4, called Strong Params.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.