0
我的应用程序将代码写入数据库时出现问题。我可以在参数中看到它,但它在提交表单后不会在数据库中看到它。未写入数据库的多态嵌套属性
我创建了一个我想添加到课程对象中的地址对象。
型号
class Course < ActiveRecord::Base
has_one :address, :as => :addressable
accepts_nested_attributes_for :address
// more code
end
class Address < ActiveRecord::Base
belongs_to :addressable, :polymorphic => true
end
控制器
class CoursesController < ApplicationController
def course_params
params.require(:course).permit(:short_description, :picture, :name, :cost, :description, :occurs_at, address_attributes: [:line1, :line2, :city, :state, :zip])
end
def create
@course = current_user.courses.build(course_params)
@course.build_address
if @course.save
flash[:success] = "Course created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
//No address controller
我试图build_address呼叫转移到内保存,它似乎写入数据库,但实际上没有关联的两个... ...
帮手
module FormHelper
def setup_course(course)
course.address ||= Address.new
course
end
end
查看
<%= form_for(setup_course(@course), html: { multipart: true }) do |f| %>
<%= f.fields_for :address do |address| %>
<%= render :partial => 'shared/address', :locals => {:f => address} %>
<% end %>
<% end %>
数据库控制台
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KKDEbmm7vBFjDR6KPHn29ZbroA6FyLtkUaJhBu5kAELeL1Zs89WmonpDH8wCCqtFeiMDXxypJwsHv/ck5wbznA==", "course"=>{"name"=>"11", "short_description"=>"fdsaf0dsa3f032ds", "description"=>"f03dsaf1dsa01", "occurs_at"=>"<date>", "cost"=>"", "address_attributes"=>{"line1"=>"aa", "line2"=>"bb", "city"=>"cc", "state"=>"wa", "zip"=>"12345"}}, "commit"=>"Create Course"}
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "courses" ("short_description", "name", "description", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?) [["short_description", "fdsaf0dsa3f032ds"], ["name", "11"], ["description", "f03dsaf1dsa01"], ["user_id", 1], ["created_at", "2016-05-27 02:33:31.234818"], ["updated_at", "2016-05-27 02:33:31.234818"]]
SQL (0.4ms) INSERT INTO "addresses" ("addressable_type", "addressable_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["addressable_type", "Course"], ["addressable_id", 17], ["created_at", "2016-05-27 02:33:31.247646"], ["updated_at", "2016-05-27 02:33:31.247646"]]
(13.6ms) commit transaction
我运行轨道4
谢谢您的帮助!
什么是您的CoursesController创建的操作方法是什么样子? – Anand
你确定吗?日志显示记录被插入到课程和地址中。 – max
我在courses_controller中添加了create。 @Anand – bralyan