Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 实例化一个ruby类没有初始化方法,但是使用attr\u accesors?_Ruby On Rails_Ruby_Railsapps_Learn Ruby On Rails - Fatal编程技术网

Ruby on rails 实例化一个ruby类没有初始化方法,但是使用attr\u accesors?

Ruby on rails 实例化一个ruby类没有初始化方法,但是使用attr\u accesors?,ruby-on-rails,ruby,railsapps,learn-ruby-on-rails,Ruby On Rails,Ruby,Railsapps,Learn Ruby On Rails,下面的代码可以工作,但我不明白为什么 模型:我有一个名为Contact的类,它没有initialize方法(即它从默认对象类继承initialize方法) 控制器:我有一个带有“create”方法的ContactsController,该方法实例化Contact类,通过“secure_params”方法传递一些参数 class ContactsController < ApplicationController def new @contact = Contact.new

下面的代码可以工作,但我不明白为什么

模型:我有一个名为Contact的类,它没有initialize方法(即它从默认对象类继承initialize方法)

控制器:我有一个带有“create”方法的ContactsController,该方法实例化Contact类,通过“secure_params”方法传递一些参数

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
class contacts控制器
如果没有将这些参数设置为实例变量的initialize方法,并且“new”方法(继承自Ruby的对象类)的默认行为对传入的参数没有任何影响,那么这些参数将转到哪里


为什么它们最终被设置为实例变量?(与属性有关?

您包括定义设置值的方法的
ActiveModel::Model

您包括定义设置值的方法的
ActiveModel::Model

太好了!谢谢你的回答!伟大的谢谢你的回答!
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