我无法弄清楚我做错了什么,但我的嵌套表格不会保存到我的房间桌子上。
这是我的观点
<h1>Room Assignments</h1>
<p>
<%= form_for @member do |f| %>
<%= f.label :name, "Member name" %><br>
<%= f.text_area :name %><br>`enter code here`
<%= f.fields_for :room do |b| %>
<%= b.label :room_name %><br>
<%= b.text_area :room_name %><br>
<%= b.label :rent %><br>
<%= b.text_area :rent %><br>
<% end %>
<%= f.submit "Submit" %>
<% end %>
class MembersController < ApplicationController
def new
@member = Member.new
@member.purchases.build
@room = @member.build_room
end
def index
@member = Member.all
end
def create
@member = Member.create(member_params)
@room = @member.create_room
if @member.save
redirect_to new_purchase_url
else
render :new
end
end
def show
@member = Member.find(params[:id])
end
def member_params
params.require(:member).permit(:name, :room_id,
room_attributes: [:rent, :name, :id, :member_id],
purchase_attributes: [:description, :cost, :id, :member_id])
end
end
class Member < ActiveRecord::Base
belongs_to :room
has_many :purchases
accepts_nested_attributes_for :purchases, :room
end
class Room < ActiveRecord::Base
has_one :member, foreign_key: "member_id"
has_many :purchases
end
当我检查它是否已保存时,这是在rails控制台中输出的内容:
2.0.0-p451 :070 > Member.last
Member Load (0.3ms) SELECT "members".* FROM "members" ORDER BY "members"."id" DESC LIMIT 1
=> #<Member id: 24, name: "Tom", room_id: 38>
2.0.0-p451 :071 > Room.last
Room Load (0.3ms) SELECT "rooms".* FROM "rooms" ORDER BY "rooms"."id" DESC LIMIT 1
=> #<Room id: 38, room_name: nil, rent: nil, member_id: nil>
答案 0 :(得分:0)
问题是您在创建操作中调用了@room = @member.create_room
。前一行应该已经拉入参数并构建了成员和房间实例。因此,当您致电create_room
时,您实际上正在更换添加了新(空白)房间的房间。这就是我要做的事情:
def create
@member = Member.new(member_params)
if @member.save
redirect_to new_purchase_url
else
render :new
end
end