请帮我解决此错误并重新编辑我的所有页面。实际上我是Ruby on Rails的新手,我使用rails版本-4和ruby版本1.9.3。我想显示一个表单,包括选择选项和保存在DB中的选定值。我的错误和代码片段在下面解释。
错误:
undefined method `email_providers=' for #<Class:0x4e68df0>
Extracted source (around line #2):
1 class Contact < ActiveRecord::Base
2 self.email_providers = %w[Gmail Yahoo MSN]
3 validates :email_provider, :inclusion => email_providers
4 end
视图/联系人/ index.html.erb
<%= form_for @contact,:url => {:action => "create"} do |f|%>
<%= f.text_field:gmail %>
<%= f.select :email_provider, options_for_select(Contact.email_providers, @contact.email_provider) %>
<%= f.submit "Submit"%>
<% end %>
控制器/ contacts_controller.rb
class ContactsController < ApplicationController
def index
@contact=Contact.new
end
def create
end
end
模型/ contact.rb
class Contact < ActiveRecord::Base
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
end
迁移/ 20141222061313_create_contacts.rb
class CreateContacts < ActiveRecord::Migration
def change
create_table :contacts do |t|
t.string :gmail
t.string :yahoo
t.string :msn
t.timestamps
end
end
end
我想在选项下拉列表中显示3个内容(gmail,yahoo,msn),当它被选中并单击提交按钮时,它将保存在DB中。请帮我编辑代码。谢谢推进..
答案 0 :(得分:1)
更改
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
在您的Contact模型类中:
EMAIL_PROVIDERS = %w{Gmail Yahoo MSN}
validates :email_provider, inclusion: {in: EMAIL_PROVIDERS}
并且应该修复错误。
您可以猜到,您的Contact类没有self.email_providers=
方法。因此,尝试通过此方法为其分配值将会崩溃。我所做的是创建一个常量,可以通过EMAIL_PROVIDERS
在课堂上通过Contact::EMAIL_PROVIDERS