好吧,所以我有兩個表的軌道嵌套窗體。它將所有內容插入到一個表格中,但不在另一個表格中。我查了一下所有的例子,我可以得到我的手,無論我做什麼似乎都不起作用。Rails嵌套窗體沒有插入到數據庫中
這裏是我的模型:
用戶:
class User < ActiveRecord::Base
has_many :addresses, dependent: :destroy
accepts_nested_attributes_for :addresses
end
地址:
class Address < ActiveRecord::Base
belongs_to :user
end
這是我的形式:
= form_for @user do |f|
- if @user.errors.any?
#error_explanation
%h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
%ul
- @user.errors.full_messages.each do |msg|
%li= msg
%ul
.field
= f.label :first_name
= f.text_field :first_name
.field
= f.label :last_name
= f.text_field :last_name
.field
= f.label :password
= f.text_field :password
.field
= f.label :email
= f.text_field :email
= f.fields_for :address do |address|
.field
= address.label :country
= address.text_field :country
.field
= address.label :state
= address.text_field :state
.field
= address.label :city
= address.text_field :city
.field
= address.label :zip_code
= address.text_field :zip_code
.actions
= f.submit 'Save'
最後還有控制器,這是我相信是我的來源問題,我已經查閱了無數的例子,如何做到這一點,似乎每個人都做不同的事情。反正這裏是:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
@user = User.new
@addresses = @user.addresses.build
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name, :password, :email,
address_attributes: [:country, :state, :city])
end
end
@阿古斯,太好了。我建議你檢查我提到的寶石。 – Emu
我會這樣做的。謝謝。 – Argus