我是 Rails 的新手,我已经开始开发我的第一个应用程序,但遇到了一个我无法解决的问题。
基本上我正在跟踪出租物业,所以我有房屋、租户、租赁、供应商、维修等的控制器和模型。我已经能够设置所有这些并从网络表单创建新记录、更新、编辑等除了一个叫 TENANTS 的人。
由于我无法从 Web 表单中获取应用程序的保存记录 - 我转到 Rails 控制台并遇到了同样的问题。我无法从控制台保存到数据库。
我在控制台中创建新“租户”记录的示例
tenant = Tenant.new
=> #<Tenant id: nil, first_name: nil, last_name: nil, home_id: nil, created_at: nil, updated_at: nil>
>> first_name = "Billy"
=> "Billy"
>> last_name = "Jones"
=> "Jones"
>> tenant.save
(0.1ms) BEGIN
SQL (0.2ms) INSERT INTO `tenants` (`created_at`, `first_name`, `home_id`, `last_name`, `updated_at`) VALUES ('2012-07-29 20:54:28', NULL, NULL, NULL, '2012-07-29 20:54:28')`
Mysql2::Error: Column 'first_name' cannot be null: INSERT INTO `tenants` (`created_at`, `first_name`, `home_id`, `last_name`, `updated_at`) VALUES ('2012-07-29 20:54:28', NULL, NULL, NULL, '2012-07-29 20:54:28')
(0.1ms) ROLLBACK
ActiveRecord::StatementInvalid: Mysql2::Error: Column 'first_name' cannot be null: INSERT INTO `tenants` (`created_at`, `first_name`, `home_id`, `last_name`, `updated_at`) VALUES ('2012-07-29 20:54:28', NULL, NULL, NULL, '2012-07-29 20:54:28')
SO, I cannot determine the problem. It says first_name cannot be null, obviously because I setup the database that way, but there is a value trying to go into database, even though I can return a value in Rails Console asking for first_name..... Any advise?
Below are controller/model
***** TENANT CONTROLLER
class TenantsController < ApplicationController
def index
render('list')
end
def list
@tenants = Tenant.order("tenants.last_name ASC")
end
def show
@tenant = Tenant.find(params[:id])
end
def new
@tenant = Tenant.new
end
def create
@tenant = Tenant.new(params[:tenant])
@tenant.save
if @tenant.save
flash[:notice] = "New Tenant was created successfully."
redirect_to(:action => 'list')
else
render('new')
end
end
def edit
@tenant = Tenant.find(params[:id])
end
def update
# find object using form parameters
@tenant = Tenant.find(params[:id])
#update the object
if @tenant.update_attributes(params[:tenant])
#if update succeeds redirect to
flash[:notice] = "Tenant was updated successfully."
redirect_to(:action => 'show', :id => @tenant.id)
else
render('edit')
end
end
def delete
@tenant = Tenant.find(params[:id])
end
def destroy
@tenant = Tenant.find(params[:id])
@tenant.destroy
flash[:notice] = "Tenant was destroyed successfully."
redirect_to(:action => 'list' )
end
end
***** TENANT MODEL
class Tenant < ActiveRecord::Base
attr_accessible :first_name, :last_name, :home_id
end