我有一个包含service_provider
和service
模型的程序。 service_provider
使用has_many
归因,service
模型使用belongs_to
归因。 service_provider
是使用设计创建的。我无法在service_provider_id
方法中为服务分配create
。
services_controller.rb
def create
@service = Service.new(service_params)
@service.service_provider_id = current_service_provider.id
respond_to do |format|
if @service.save
format.html { redirect_to @service, notice: 'Service was successfully created.' }
format.json { render :show, status: :created, location: @service }
else
format.html { render :new }
format.json { render json: @service.errors, status: :unprocessable_entity }
end
end
end
rails控制台为每项服务提供service_provider_id: nil
。
schema.rb
service_provider_id
使用迁移创建了t.belongs_to :service_provider, index: true
" create_table "service_providers", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "service_providers", ["email"], name: "index_service_providers_on_email", unique: true
add_index "service_providers", ["reset_password_token"], name: "index_service_providers_on_reset_password_token", unique: true
create_table "services", force: :cascade do |t|
t.integer "service_provider_id"
t.string "service_name"
t.text "description"
t.integer "price"
t.string "location"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "services", ["service_provider_id"], name: "index_services_on_service_provider_id"
"
service.rb
这是class Service < ActiveRecord::Base
attr_accessor :service_provider_id
belongs_to :service_provider
validates_presence_of :description, :location, :service_name, :price
end
型号
class ServiceProvider < ActiveRecord::Base
has_many :services
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
&#39; service_provider.rb`
{ endDate=2015-10-19 19:00:00.0}
我尝试重启服务器并重置数据库没有运气。
答案 0 :(得分:0)
仅从attr_accessor :service_provider_id
service.rb
rake db:migrate
然后rails s
正如@Petr提到的那样覆盖(称为nil
的第二次)。