私のコードでは、「has_many => belongs_to」モデルの関連付けと、新しいアクションのビューにネストされたフォームがあることがわかります。
さらに、Railsフォームハンドラーで同じパラメーターに2つの別々のフィールドを使用しましたか?
問題は、「prix」属性 (「Projet」モデル) がデータベースに記録されますが、「nom」属性 (「Activite」モデル) は記録されないことです。
問題は強力なパラメータにあるのかもしれませんが、私のコードではすべて問題ないと思います...または、リンクした他のStackoverflowの質問で見つけたコードの中にあるかもしれません。
私のコードにはフランス語の単語があります: activite は活動、projet はプロジェクト、nom は名前、prix は価格、非常に簡単です :)
ご協力いただきありがとうございます !
アプリ/モデル/projet.rb:
class Projet < ActiveRecord::Base
has_many :activites
accepts_nested_attributes_for :activites,
reject_if: lambda {|attributes| attributes['nom'].blank?}
end
アプリ/モデル/activite.rb:
class Activite < ActiveRecord::Base
belongs_to :projet
def acttext=(value)
@acttext = value if value
prepare_act
end
def actselect=(value)
@actselect = value if value
prepare_act
end
def acttext
@acttext || self.nom
end
def actselect
@actselect || self.nom
end
private
def prepare_act
self.nom = acttext if acttext
self.nom = actselect if actselect
end
end
app/controllers/projets_controller.rb :
class ProjetsController < ApplicationController
def new
@projet = Projet.new
@activites_options = Activite.pluck(:nom).uniq
2.times { @projet.activites.new}
end
def create
@projet = Projet.new(projet_params)
if @projet.save
redirect_to @projet
else
render 'new'
end
end
private
def projet_params
params.require(:projet).permit(:prix, activites_attributes: [:id, :nom, :heures, :minutes, :acttext, :actselect])
end
end
app/views/projets/new.html.erb :
<div>
<%= form_for @projet do |f| %>
<%= f.label :prix %><br>
<%= f.text_area :prix %><br>
<ul>
<%= f.fields_for :activites do |activites_form| %>
<li>
<%= activites_form.label :choisissez_un_type_dactivité %>
<%= activites_form.select :actselect, @activites_options, {include_blank: true} %>
<%= activites_form.label :ou_créez_en_un_nouveau %>
<%= activites_form.text_field :acttext %><br>
<%= activites_form.label :heures %>
<%= activites_form.text_field :heures %>
<%= activites_form.label :minutes %>
<%= activites_form.text_field :minutes %>
</li>
<br>
<% end %>
</ul>
<p><%= f.submit "Créer le projet" %></p>
<% end %>
</div>