开发者

Simple Rails validation issue with non-user defined inputs

开发者 https://www.devze.com 2023-01-30 18:53 出处:网络
Background I\'m using the acts_as_list gem in a rails app my posts table has a position column position is assigned in a before_create callback in my model:

Background

  • I'm using the acts_as_list gem in a rails app
  • my posts table has a position column
  • position is assigned in a before_create callback in my model:

This is the code for my Post model:

class Post < ActiveRecord::Base    
  acts_as_list
  before_create :set_position
  attr_accessible :title, :description, :category_id
  validates :position, :presence => true, :uniqueness => true 

  protected
    def set_position
      self.position = Post.all.size + 1
    end
end

My Problem: I don't want users开发者_开发问答 to be able to set the position, so I've removed the position field from the Post form. When I submit a new post, the validation fails, and I'm told that position can't be blank.

I realise that my validation is failing because the user is not inputting the position themselves, but I have set the position in the before_filter, so how can I get rails to use that information when it is performing the validation?

Bonus Question The form submits when I remove the validation, but I was wondering why this works because I don't pass position to attr_accessible? I pass a number of other symbols to it like so: attr_accessible :title, :description, :category_id but I don't pass :position. Is there likely to be any problems there? Should position be attr_protected?


First question

before_validation :set_position, :on => :create

Bonus question. You probably got mass assigment warrning (check your logs) When you remove validation rails dont return any error on :position so they save what was in attr_accesible (probably the position will be null in DB)

0

精彩评论

暂无评论...
验证码 换一张
取 消