事象
2つのモデルを同時登録をしたいため、
accepts_nested_attributes_forを利用しているんですが、
permitがうまくいかず・・・。
試行錯誤して色々、2時間〜3時間探したんですが
解決できていないので、こちらで質問させていただきました。
環境
Rails 5.0.0.1
Model
モデルはOfficeとUserの2つのモデルを用意しています。
ruby
1class Office < ApplicationRecord 2 has_many :users 3 accepts_nested_attributes_for :users 4 5 validates :name, uniqueness: true, presence: true 6 validates :format, presence: true 7end 8 9class User < ApplicationRecord 10 belongs_to :office 11 12end
Controller
コントローラーではOfficeを中心にネストさせたUserを登録する形にしています。
class OfficesController < ApplicationController def new @office = Office.new @office.users.build end def create Office.create(office_params) redirect_to root_path end private def office_params params.require(:office).permit(:name,:format,users_attributes: [:name,:email,:office_id]) end end
#View
<%= form_for :office do |f| %> <table> <tbody> <tr> <td>会社名</td> <td><%= f.text_field :name %></td> </tr> <tr> <td>法人/個人</td> <td><%= f.select :format, {"法人" => true, "個人" => false} %></td> </tr> <tr> <%= f.fields_for :users do |u| %> <td>ユーザー名</td> <td><%= u.text_field :name %></td> </tr> <tr> <td>メールアドレス</td> <td><%= u.text_field :email %></td> </tr> <% end %> </tbody> </table> <%= f.submit %> <% end %>
うまくいかないこと
Officeは登録されるんですが、UserがPermitされず、登録できない事象にぶつかっています。原因なのではと考えていることがparamsがusers_attributesとしているんですが、usersで出力されてしまっており、そのあたりが関連しているのではないかと思うのですが・・・。
サーバーログ
Started POST "/signup" for ::1 at 2017-01-12 22:55:42 +0900 Processing by OfficesController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"xxxxxx", "office"=>{"name"=>"test", "format"=>"true", "users"=>{"name"=>"test", "email"=>"test@test.com"}}, "commit"=>"Save Office"} Unpermitted parameter: users (1.6ms) BEGIN Office Exists (22.5ms) SELECT 1 AS one FROM `offices` WHERE `offices`.`name` = BINARY 'test' LIMIT 1 SQL (5.4ms) INSERT INTO `offices` (`name`, `created_at`, `updated_at`) VALUES ('test', '2017-01-12 13:55:43', '2017-01-12 13:55:43') (5.9ms) COMMIT Redirected to http://localhost:3000/ Completed 302 Found in 203ms (ActiveRecord: 35.5ms)
誰かお分かりになられる方教えていただけると嬉しいです!
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/01/14 13:12