将数组插入字符串

时间:2014-04-23 20:13:46

标签: ruby-on-rails ruby ruby-on-rails-4

Ruby on Rails 4

我的表单是将属性提交到表中,一个属性(:permission)是一个字符串数组。我得到的错误是它无法插入数组以输入字符串,因此我尝试添加to_s并且错误消失但现在它已回滚。我不确定如何查看错误或如何解决此问题。

我的表格:

<%= f.label :permission, "Permission Level" %>
<%= f.select :permission, [ ["Read Only", "read"], ["IP Voice Telephony", "ip_voice"], ["IP Video Telephony", "ip_video_telephony"], ["Enterprise Gateways", "enterprise_gateways"], ["Consumer ATAs", "consumer_atas"], ["IP PBX", "ip_pbx"], ["Master of All", "all"] ], {prompt: "Select Permission Level"}, {:multiple => true, class: "input-lg"} %>

我的控制器:

def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation, :admin, :permission => [].to_s)
end

我的日志:

Started POST "/users" for 24.147.48.156 at 2014-04-23 13:06:05 -0700
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"spaGUvxtoK2ipPrSkmGmMuIChVcEtzrWJbt/b1oByG4=", "user"=>{"name"=>"Tester", "email"=>"t
est@x.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "permission"=>["", "ip_voice", "ip_video_telephon
y"], "admin"=>"0"}, "commit"=>"Create User"}
(0.1ms)  begin transaction
User Exists (0.1ms)  SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('test@x.com') LIMIT 1
(0.1ms)  rollback transaction

我不确定如何插入数组或如何查看错误,任何帮助表示赞赏。

用户模型:

class User < ActiveRecord::Base
before_save { self.email = email.downcase }
before_create :create_remember_token
has_many :questions
serialize :permission

validates :name, presence: true, length: { maximum: 50 }
validates :permission, presence: true

VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, 
                            uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }                         


has_secure_password

def User.new_remember_token
    SecureRandom.urlsafe_base64
end

def User.hash(token)
    Digest::SHA1.hexdigest(token.to_s)
end

private 

    def create_remember_token
        self.remember_token = User.hash(User.new_remember_token)
    end
end

1 个答案:

答案 0 :(得分:2)

我认为您正在寻找serialize权限属性

在您的用户模型中

class User < ActiveRecord::Base
  serialize :permission
end

这告诉Rails将在Rails层上作为Array对象处理的权限属性转换为数据库层中的String对象。


编辑1:

尝试编辑user_params方法。

def user_params
  params.require(:user).permit(:name, :email, :password, :password_confirmation, :admin, :permission => [] )
end