Answer the question
In order to leave comments, you need to log in
How to create a nested rails form?
In general, I forgot. It worked before.
Two models A and B. B is nested in A.
app/models/a.rb
class A < ActiveRecord::Base
has_one :b, dependent: :destroy
accepts_nested_attributes_for :b
end
app/models/b.rb
class B < ActiveRecord::Base
belongs_to :a
end
db/migrate/..rb
class Ab < ActiveRecord::Migration
def change
create_table(:as) do |t|
t.string :a_field, default: ""
end
create_table(:bs) do |t|
t.integer :a_id
t.string :b_field, default: ""
end
end
end
app/controllers/test2_controller.rb
class Test2Controller < ApplicationController
def edit
@a = A.all.first
@b = @a.b
render "ab_form"
end
def update
# params[:a][:b_attributes] = {}
# params[:a][:b_attributes][:b_field] = 'a'
@a = A.where(:id => 1).first
@a.update(params.require(:a).permit(:a_field, b_attributes: [:b_field]))
redirect_to edit_a_path
end
end
views/test2/ab_form.html.haml
=simple_form_for @a, :url => :update_a do |f|
=f.input :a_field
=f.simple_fields_for @b do |g|
=g.input :b_field
=f.button :submit
config/routes.rb
get '/тест2/форма', :to => 'test2#edit', :as => :edit_a
patch '/тест2/записать', :to => 'test2#update', :as => :update_a
<form class="simple_form edit_a" id="edit_a_1" action="/%D1%82%D0%B5%D1%81%D1%822/%D0%B7%D0%B0%D0%BF%D0%B8%D1%81%D0%B0%D1%82%D1%8C" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓"><input type="hidden" name="_method" value="patch"><input type="hidden" name="authenticity_token" value="Yuh+fMJMZ+OdHClUcyHoFLdBXp/w/Pnio4kAP64wVgL+uDi/GCZtvCO1p5opB44X3lSE8/4LjcBuwZLgxNzNJg=="> <div class="input string optional a_a_field"><label class="string optional" for="a_a_field">A field</label><input class="string optional" type="text" value="asff2" name="a[a_field]" id="a_a_field"></div>
<div class="input string optional a_b_b_field"><label class="string optional" for="a_b_b_field">B field</label><input class="string optional" type="text" value="a" name="a[b][b_field]" id="a_b_b_field"></div>
<input type="submit" name="commit" value="Сохранить A" class="button">
</form>
Answer the question
In order to leave comments, you need to log in
=simple_form_for @a, :url => :update_a do |f|
=f.input :a_field
=f.simple_fields_for :b, @b do |g|
=g.input :b_field
=f.button :submit
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question