扶手:attr_accessor中和attr_accessible区别 [英] Rails: difference between attr_accessor and attr_accessible

查看:109
本文介绍了扶手:attr_accessor中和attr_accessible区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别?另外,为什么这不工作:

What is the difference? Also, why does this not work:

如BASE_PATH的变量没有被设置。

The variables such as base_path are not being set.

class Cvit < ActiveRecord::Base
  attr_accessible :species,:program,:textup,:e_value,:filter,:min_identity,:cluster_dist,:fileup_file_name
  attr_accessor :base_path, :fa_file, :text_file, :dbase, :source, :bl_file, :bl_sorted, :gff_file, :cvt_file, :db, :overlay_coords_gray

  def initilize(*args)
     super(*args)
  end

  def cvitSetup()
    self.base_path = "blast_cvit/"
    self.fa_file = "input.fa"
    .
    .
  end
end

在轨不过安慰的属性得到正确设置,当我尝试这样做:

in the rails console the attributes get set correctly however when I try to do this:

控制器:

def show
    @cvit = Cvit.find(params[:id])
    @cvit.cvitSetup()
    @cvit.blast()
    @cvit.generateGff()
    @cvit.generateCvitImage()


    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @cvit }
    end
  end

在我看来,我引用@ cvit.some_attribute.html_safe但该属性为空,所以我得到一个错误。任何想法?

and in my view I reference @cvit.some_attribute.html_safe but that attribute is null so I get an error. Any ideas?

推荐答案

attr_accessor中创建的getter method.attribute 和setter method.attribute = 指定的属性。

attr_accessor creates the getter method.attribute and setter method.attribute= for the specified attributes.

attr_accessible 是的ActiveRecord :: Base和指定型号的白名单属性,可以通过大规模的分配进行设置。参见文档和示例<一个href=\"http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_accessible\"相对=nofollow>这里。

attr_accessible is from ActiveRecord::Base and "Specifies a white list of model attributes that can be set via mass-assignment." See documentation and example here.

编辑:

关于你的第二个问题,我不知道。我想这个虚拟code和它的工作:

As for your second question, I don't know. I tried this dummy code and it worked:

class Test
attr_accessor :base_path, :fa_file
  def cvitSetup()
    self.base_path = "blast_cvit/"
    self.fa_file = "input.fa"
  end
end
t = Test.new
t.cvitSetup
p t.base_path
#=> "blast_cvit/"

您确保正确初始化类?

这篇关于扶手:attr_accessor中和attr_accessible区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆