【发布时间】:2015-03-04 18:34:33
【问题描述】:
以下代码有效,但我不明白为什么。
模型:我有一个名为 Contact 的类,它没有初始化方法(即它从默认的 Object 类继承初始化方法)。
class Contact
include ActiveModel::Model
attr_accessor :name, :string
attr_accessor :email, :string
attr_accessor :content, :string
validates_presence_of :name
validates_presence_of :email
validates_presence_of :content
...
end
控制器:我有一个带有“create”方法的 ContactsController,它实例化通过“secure_params”方法传递一些参数的 Contact 类。
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
# THIS IS THE LINE THAT I DON'T UNDERSTAND
@contact = Contact.new(secure_params)
if @contact.valid?
@contact.update_spreadsheet
UserMailer.contact_email(@contact).deliver
flash[:notice] = "Message sent from #{@contact.name}."
redirect_to root_path
else
render :new
end
end
private
def secure_params
params.require(:contact).permit(:name, :email, :content)
end
end
如果没有将参数设置为实例变量的初始化方法,并且“new”方法(继承自 Ruby 的 Object 类)的默认行为对传入的参数没有任何作用,那么这些参数会去哪里?
为什么它们最终被设置为实例变量? (与 attr_accesors 有关吗?)
【问题讨论】:
标签: ruby-on-rails ruby railsapps learn-ruby-on-rails