attr_accessor没有工作Rails 4

时间:2014-05-29 06:33:19

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

我的代码出现问题。我想,这段代码是正确的,但我不知道会发生什么?这是我的代码:

registration.rb:

class Registration < ActiveRecord::Base
  attr_accessor :create_registration, :is_contact_registration, :is_appointment_registration

  validates :client_id, presence: true
  validates :type, presence: true
  validates :contact_thru, presence: true
  validates :purpose_message, presence: true,   :unless => :is_appointment_registration
  validates :action_needed, presence: true,     :unless => :is_appointment_registration
  validates :date_created, presence: true
  validates :owner_id, presence: true
  validates :status, presence: true
  validates :notes, presence: true  

end

我的控制器,

  def create
    binding.pry
    @registration = Registration.new(record_params)
    @registration.owner_id = current_user.id

    @registration.is_appointment_registration = true
    if @registration.save
      render json: @registration, status: :created, location: @registration
    else
      render json: @registration.errors, status: :unprocessable_entity
    end

  end

问题是,当我将数据放在:notes:place上时,验证仍然失败。请帮帮我们。谢谢!

2 个答案:

答案 0 :(得分:2)

  

问题是,当我将数据放在:notes和:place时,它会返回错误   即使我有数据输入。请帮帮我们。

您的attr_accessor不包含:notes:place。除非您将这些属性作为数据库列,否则您需要在attr_accessor块中将它们声明为虚拟属性:

attr_accessor :create_registration, :is_contact_registration, :is_appointment_registration, :notes, :place

答案 1 :(得分:0)

Rails 4取消了attr_accessor(位于模型上),取而代之的是控制器中包含的强参数。您需要更新代码,将所有字段从attr_accessor移动到控制器中的params,如下所示:

def create
    ModelName.new(controller_name_params)
    ...
end

private
def controller_name_params
        params.require(:controller_name).permit(
            :field1,
            :field2
        )
    end

和@Rich说的一样,请务必将所有字段添加到您希望用户能够更改的参数中。

文档中的更多信息,请访问:http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

相关问题