我不明白为什么以下不适用于Rails 3.我得到"未定义的局部变量或方法`custom_message'"错误.
validates :to_email, :email_format => { :message => custom_message }
def custom_message
self.to_name + "'s email is not valid"
end
Run Code Online (Sandbox Code Playgroud)
我也尝试使用:message =>:custom_message,而不是像rails-validation-message-error帖子中建议的那样 没有运气.
:email_format是位于lib文件夹中的自定义验证器:
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each(object, attribute, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
object.errors[attribute] << (options[:message] || 'is not valid')
end
end
end
Run Code Online (Sandbox Code Playgroud) 所以我有一些数据从控制器中的另一个rails应用程序中拉出来让我们称之为ExampleController,我想在我的模型中验证它,然后才允许向导进入下一步,我无法弄清楚如何我应该这样做(我知道直接从控制器获取这些数据到模型中违反了MVC我正在寻找从控制器获取数据的最佳解决方法).数据必须来自控制器,因为获取它的方法包含在ApplicationController中,但如果这更容易,我可以在Awizard控制器中执行此操作.(我也不能用宝石)
请提供一些问题的建议,而不是解释为什么这不是正确的做事方式我已经意识到已经但不能以另一种方式做到.
示例控制器
这应该代替渲染数据,然后检查它在其他地方是不是空白?
class ExampleController < ApplicationController
def valid_data?
data = #data could be nil or not
if data.blank?
return false
else
return true
end
end
Run Code Online (Sandbox Code Playgroud)
我的模型 - (models/awizard.rb)
我如何使用valid_data?来自示例控制器的方法?在我的验证中.
class AWizard
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Dirty
include ActiveModel::Naming
#This class is used to manage the wizard steps using ActiveModel (not ActiveRecord)
attr_accessor :id
attr_writer :current_step #used to write to current step
define_attribute_methods [:current_step] #used for marking change
validate :first_step_data, :if => lambda { |o| o.current_step …Run Code Online (Sandbox Code Playgroud) forms validation model-view-controller ruby-on-rails activemodel
有没有办法让Devise与Rails 4.0rc1一起使用?尝试启动rails服务器甚至生成Devise视图时出现以下错误:
/Users/scott/.rvm/gems/ruby-2.0.0-p195@rails/gems/activemodel-4.0.0.rc1/lib/active_model/deprecated_mass_assignment_security.rb:14:in `attr_accessible':
`attr_accessible` is extracted out of Rails into a gem. Please use new recommended protection model for params(strong_parameters) or add `protected_attributes` to your Gemfile to use old one. (RuntimeError)
Run Code Online (Sandbox Code Playgroud) ruby-on-rails attr-accessible devise activemodel ruby-on-rails-4
我一直在rails中使用普通的Ruby表单对象,但为了保持我的代码组织,我最终不得不为它们添加大量的命名空间.所以我会有一个表格,如:
class User::Registration::NewForm
extend Forwardable
extend ActiveModel::Naming
extend ActiveModel::Callbacks
include ActiveModel::Conversion
include ActiveModel::Validations
...
end
Run Code Online (Sandbox Code Playgroud)
令人烦恼的是,我的表格的param_key变得有点令人生畏,例如 user_registration_new_form
我想以某种方式覆盖它,我认为我需要从(http://apidock.com/rails/ActiveModel/Naming/param_key/class)中删除model_name和/或param_key方法.但我无法让它发挥作用.ActiveModel::Naming
有没有人能够成功覆盖模型的默认param_key?
你有一个模型,比如说,Car。一些验证Car始终适用于每个实例:
class Car
include ActiveModel::Model
validates :engine, :presence => true
validates :vin, :presence => true
end
Run Code Online (Sandbox Code Playgroud)
但是一些验证只在特定的上下文中相关,所以只有某些实例应该有它们。您想在某处执行此操作:
c = Car.new
c.extend HasWinterTires
c.valid?
Run Code Online (Sandbox Code Playgroud)
这些验证放在别处,进入不同的模块:
module HasWinterTires
# Can't go fast with winter tires.
validates :speed, :inclusion => { :in => 0..30 }
end
Run Code Online (Sandbox Code Playgroud)
如果你这样做,validates将会失败,因为它没有在Module. 如果添加include ActiveModel::Validations,那也不起作用,因为它需要包含在类中。
在不向原始类中塞入更多内容的情况下对模型实例进行验证的正确方法是什么?
完整错误如下:
ActiveModel::ForbiddenAttributesError in Admin::ProductsController#create
Run Code Online (Sandbox Code Playgroud)
我的产品型号只有一个name和price.为什么是commit参数?当我单击管理仪表板中的"创建产品"按钮时,这是参数输出:
Parameters:
{"utf8"=>"?",
"authenticity_token"=>"6/pCeklsaik4sYF5h8+WRPddkH7wJn9ZJHd6YLaaNuc=",
"product"=>{"name"=>"Black Shirt Male",
"price"=>"25"},
"commit"=>"Create Product"}
Run Code Online (Sandbox Code Playgroud)
从我收集到的其他Stack Overflow帖子中,您需要在Rails 4中使用强参数而不是attr_accessible,当我搭建产品模型时,这是为我完成的.在我create的Products控制器中,我有:
@product = Product.new(product_params)
Run Code Online (Sandbox Code Playgroud)
product_params定义为:
def product_params
params.require(:product).permit(:name, :price)
end
Run Code Online (Sandbox Code Playgroud)
我创建模型时没有做任何想象,在我的Gemfile中我使用以下作为Rails 4的文档建议:
gem 'stripe', :git => 'https://github.com/stripe/stripe-ruby'
Run Code Online (Sandbox Code Playgroud)
当我通过Active Admin仪表板创建新产品时,为什么会出现此错误?关于此事的任何意见都表示赞赏.
https://github.com/dockyard/postgres_ext-serializers
这似乎很容易设置,但我似乎无法获得任何基本功能来将JSON从rails移动到postgres.我尝试在我的ams init,我的特定序列化程序和我的模型中包含以下内容,但它似乎永远不会激活.
我在Rails 4.2.3和Ruby 2.2上
这就是我尝试添加到多个文件:
需要'postgres_ext/serializers'
非常感谢你的帮助,我知道我必须遗漏一些明显的东西.
更新:为了给出更多的上下文,你读了这个gem的README.md指令,它只是说"
只需要'postgres_ext/serializers'并像往常一样使用ActiveModel :: Serializers!
所以我在我的application.rb中添加了require'postgres_ext/serializers',对序列化器进行了一个小编辑,看它是否有效:
class UserSerializer < ActiveModel::Serializer
cached false
attributes :id, :username, :location, :full_name
def full_name
"#{object.first_name} #{object.last_name}"
end
def full_name__sql
"first_name || ' ' || email"
end
end
Run Code Online (Sandbox Code Playgroud)
然后我将在我的Rails控制台中运行以下代码:
users = User.first(10)
ActiveModel::ArraySerializer.new(users, each_serializer: UserSerializer).to_json
Run Code Online (Sandbox Code Playgroud)
但__sql全名属性从未显示过,它似乎没有从postgres中提取数据与以前有任何不同.
这就是我的application.rb看起来像:
# require 'postgres_ext/serializers' ### Doesn't work here
require File.expand_path('../boot', __FILE__)
require 'rails/all'
require 'postgres_ext/serializers'
Bundler.require(*Rails.groups)
module Baller
class Application < Rails::Application
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks …Run Code Online (Sandbox Code Playgroud) 我尝试在数据库中创建没有表的自动类型转换的新模型.我试图继承ActiveRecord::Base它抛出的异常ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "people" does not exist
课程实施:
class Person < ActiveRecord::Base
def self.columns
@columns ||= [];
end
def self.column(name, sql_type = nil, default = nil, null = true)
@columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
end
columns
column :from_email, :string
column :to_email, :string
column :article_id, :integer
column :message, :text
def initialize
end
end
Run Code Online (Sandbox Code Playgroud)
堆栈跟踪:
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "people" does not exist
LINE 8: WHERE a.attrelid = '"people"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), …Run Code Online (Sandbox Code Playgroud) 我有一个模型,Student与另一个模型有一个habtm关系,Group.以下代码:
Student.ransack(groups_id_eq: 22839).result
Run Code Online (Sandbox Code Playgroud)
生成以下SQL:
SELECT "students".* FROM "students"
LEFT OUTER JOIN "groups_students" ON "groups_students"."student_id" = "students"."id"
LEFT OUTER JOIN "groups" ON "groups"."id" = "groups_students"."group_id"
WHERE "groups"."id" = NULL
Run Code Online (Sandbox Code Playgroud)
请注意它正在转换22839为NULL
这在升级到rails 5之前有效.
我有另一种模式,User与群体有着相同的关系.当我尝试Student.ransack(groups_id_eq: 22839).result它工作并产生所需的SQL.两个模型之间的区别在于Student具有uuid id,而User
据我所知,assign_attributes(不像update_attributes)不应保存记录或就此保存任何记录。
所以当我发现提供_ids一个has_many through:关系。
考虑以下示例:
class GroupUser < ApplicationRecord
belongs_to :group
belongs_to :user
end
class Group < ApplicationRecord
has_many :group_users
has_many :users, through: :group_users
end
class User < ApplicationRecord
has_many :group_users
has_many :groups, through: :group_users
validates :username, presence: true
end
Run Code Online (Sandbox Code Playgroud)
因此,我们的用户和用户组之间是一对一的关系。
Group.create # Create group with ID 1
Group.create # Create group with ID 2
u = User.create(username: 'Johny')
# The following line inserts two `GroupUser` join objects, despite the fact
# that …Run Code Online (Sandbox Code Playgroud) activemodel ×10
activerecord ×3
forms ×3
validation ×3
activeadmin ×1
devise ×1
ransack ×1
ruby ×1
serializer ×1