我的应用程序将代码写入数据库时遇到问题。我可以在参数中看到它,但在提交表单后不会在数据库中看到它。
我创建了一个我想要添加到课程对象的地址对象。
模型
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调用移到save中,它似乎写入数据库,但实际上没有关联这两个...
辅助
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
我正在运行rails 4
感谢您的帮助!
答案 0 :(得分:0)
问题在于阿南德问的问题。这是我的创建功能的一个问题。
简单修复:
def create
@course = current_user.courses.build(course_params)
if @course.save
flash[:success] = "Course created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end