这让我很难过;由于某种原因,db使用nil字段而不是我的参数保存记录。谁能帮助我理解为什么ActiveRecord没有使用我的参数?
db migration:
class CreateRoutes < ActiveRecord::Migration
def change
create_table :routes do |t|
t.integer :user_id
t.string :start_address
t.string :end_address
t.text :waypoints
t.text :schedule
t.integer :duration
t.timestamps
end
add_index :routes, :user_id
end
end
route.rb:
class Route < ActiveRecord::Base
attr_accessor :start_address, :end_address, :waypoints, :schedule, :duration
belongs_to :user
#serialize :waypoints, :schedule
validates :user_id, presence: true
validates :start_address, presence: true
validates :end_address, presence: true
validates :schedule, presence: true
validates :duration, presence: true, numericality: { only_integer: true, greater_than: 0 }
end
routes_controller.rb:
class RoutesController < ApplicationController
.
.
.
def create
logger.debug "\n\n*** #{params[:route]} ***"
@route = current_user.routes.build(params[:route])
logger.debug "*** The route is #{@route.inspect} ***\n\n"
if @route.save
flash[:success] = "Route saved!"
redirect_to user_path(current_user)
else
render 'new'
end
end
.
.
.
end
记录器输出:
*** {"start_address"=>"123 Sample St.", "end_address"=>"321 Elpmas St.", "waypoints"=>"None", "schedule"=>"Mondays", "duration"=>"15"} ***
*** The route is #<Route id: nil, user_id: 1, start_address: nil, end_address: nil, waypoints: nil, schedule: nil, duration: nil, created_at: nil, updated_at: nil> ***
答案 0 :(得分:3)
attr_accessor
将覆盖ActiveRecord
生成的访问者,导致它们不会持久存储在数据库中 - 它们将像普通的旧Ruby属性/成员而不是元编程ActiveRecord
的魔力。
数据库属性(持久属性)可以包含attr_accessible
之类的内容。