无法在ActiveRecord模型上指定字符串列

时间:2017-02-07 07:50:15

标签: ruby-on-rails

鉴于以下stage_item.rb

class StageItem < ActiveRecord::Base
  attr_accessor :headers, :line_attributes
end

schema.rb

create_table "stage_items", force: :cascade do |t|
  t.integer  "item_id"
  t.boolean  "valid_item_id"
  t.boolean  "ok_to_clearance"
  t.string   "headers"
  t.string   "line_attributes"
  t.string   "error"
  t.datetime "created_at",      null: false
  t.datetime "updated_at",      null: false
end

StageItemsController

class StageItemsController < ApplicationController
  def new
  end

  def create
    stage_item = StageItem.new
    require 'pry-byebug'
    binding.pry
    redirect_to root_url
  end
end

为什么stage_item.item_id = 42有效但stage_item.headers = "foobar"无效?

[1] pry(#<StageItemsController>)> stage_item
=> #<StageItem id: nil, item_id: nil, valid_item_id: nil, ok_to_clearance: nil, headers: nil, line_attributes: nil, error: nil, created_at: nil, updated_at: nil>
[2] pry(#<StageItemsController>)> stage_item.headers = "foobar"
=> "foobar"
[3] pry(#<StageItemsController>)> stage_item
=> #<StageItem id: nil, item_id: nil, valid_item_id: nil, ok_to_clearance: nil, headers: nil, line_attributes: nil, error: nil, created_at: nil, updated_at: nil>
[4] pry(#<StageItemsController>)> stage_item.item_id = 42
=> 42
[5] pry(#<StageItemsController>)> stage_item
=> #<StageItem id: nil, item_id: 42, valid_item_id: nil, ok_to_clearance: nil, headers: nil, line_attributes: nil, error: nil, created_at: nil, updated_at: nil>

2 个答案:

答案 0 :(得分:1)

由于您拥有stage_items

,因此您不需要该行
attr_accessor :headers, :line_attributes

我认为这会让你感到烦恼

答案 1 :(得分:0)

请删除:attr_accessor中的标题,因为列&#34;标题&#34;已经是attr_accessible了。

由于