该怎么办
- Rails6
- 使用form_with
- fields_for
- 一次注册多个模型
做
什么是fields_for
允许您以
形式编辑不同的模型
https://railsdoc.com/page/fields_for
1 2 3 4 5 6 7 8 9 10 11 | <%= form_with model: @post, url: posts_path do |form| %> <label for="name" class="block text-gray-700 text-sm font-bold mb-4">スケジュール登録</label> <%= form.text_area :name, id: "name", class: "form_style border_or w-full mb-4 focus:outline-none focus:shadow-outline" %> <%= form.text_area :user_id, class: "hidden", value: @current_user.id %> <%= fields_for :event do |event_form| %> <%= event_form.text_area :event_name, id: "event_name", class: "form_style border_or w-full mb-4 focus:outline-none focus:shadow-outline" %> <% end %> <div class="flex items-center justify-between"> <%= form.submit "登録する", class: "bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" %> </div> <% end %> |
将以下内容放在form_with标记中,如上
1 | fields_for モデル名 do || |
在亲子关系的情况下
如果form_with的模型和指定了fields_for的模型具有父子关系,则需要以下内容
模型/ oya.rb
1 | belongs_to :post |
模型/ kodomo.rb
1 | has_many :events |
controller.rb
1 2 3 | def create @event = @post.events.new(id: params[:id]) end |
参考文章
" [Rails 5]批量注册模型的过程"
https://qiita.com/Ryoga_aoym/items/91a3940cfa4de268fca4
"以一种形式处理多个模型[Ruby on Rails]"
https://www.petitmonte.com/ruby/multiple_models.html