私は新しいdo railsとMVCです。シンプルフォームと入れ子式の宝石を使って入れ子にしたフォームを自分のデータベースに保存しようとしています。 フォームを送信すると、「親」モデルのみが作成され、保存されます。 ありがとうございます。ネストされたフォームは保存されません
'親モデル':
class Diet < ApplicationRecord
belongs_to :coach
has_many :user_eat_diets
has_many :user, through: :user_eat_diets
accepts_nested_attributes_for :user_eat_diets
has_many :diet_composes
has_many :foods, through: :diet_composes
accepts_nested_attributes_for :diet_composes
end
'子' モデル:
class DietCompose < ApplicationRecord
belongs_to :diet
belongs_to :food
end
'親' コントローラ:
class DietsController < ApplicationController
def new
@diet = Diet.new
@diet.diet_composes.build
end
def create
@diet = Diet.new(diet_params)
if @diet.save
flash[:success] = "success"
end
end
def diet_params
params.require(:diet).permit(:name, :coach_id, :diet_composes_attributes)
end
end
'子' コントローラ:
class DietComposesController < ApplicationController
def new
@diet_compose = Diet_compose.new
end
def create
@diet_compose = Diet_compose.new(diet_compose_params)
if @diet_compose.save
flash[:success] = "success"
end
end
def diet_compose_params
params.require(:diet_compose).permit(:quantity, :hour, :day, :food_id, :diet_id)
end
end
フォームビュー:レールコンソール上
<%= simple_form_for @diet, :html => {:class => 'form-basic' } do |f| %>
<%= f.input :name %>
<%= f.input :coach_id %>
<%= f.nested_fields_for :diet_composes do |ff| %>
<%= ff.remove_nested_fields_link %>
<%= ff.input :hour %>
<%= ff.input :day %>
<%= ff.input :food_id %>
<%= ff.input :diet_id %>
<% end %>
<%= f.add_nested_fields_link :diet_composes %>
<%= f.button :submit %>
<% end %>
また、私はコマンドを実行します
Diet_compose.all
私はあなたがここに複数のものを修正する必要があるエラー
LoadError: Unable to autoload constant Diet_compose, expected /home/tanaka/Desktop/E-xercite/app/models/diet_compose.rb to define it from (irb):8
ありがとう!しかし、私は "attr_accessible:diet_composes"の外観を削除する必要がありました。それは、レール4.0+では存在しないようです。もう1つthinh私はどのように私が設定したdiet_idのdiet_idを、私がフォームで作成したdiet_idと等しくなるように自動設定できますか? – tanaka