Rails:attr_accessor 和 attr_accessible 之间的区别
有什么区别?另外,为什么这不起作用:
未设置诸如 base_path 之类的变量。
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
在 Rails 控制台中,属性设置正确,但是当我尝试执行以下操作时:
controller:
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 但该属性为 null,所以我收到错误。有什么想法吗?
What is the difference? Also, why does this not work:
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:
controller:
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
and in my view I reference @cvit.some_attribute.html_safe but that attribute is null so I get an error. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
attr_accessor
为指定属性创建 gettermethod.attribute
和 settermethod.attribute=
。attr_accessible
来自 ActiveRecord::Base 并且“指定可以通过批量分配设置的模型属性白名单。”请参阅此处的文档和示例。编辑:
至于你的第二个问题,我不知道。我尝试了这个虚拟代码并且它起作用了:
您确定您正确实例化了您的类吗?
attr_accessor
creates the gettermethod.attribute
and settermethod.attribute=
for the specified attributes.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.EDIT:
As for your second question, I don't know. I tried this dummy code and it worked:
Are you sure that you properly instantiated your class?
attr_accessor
只是为属性创建一个 getter-setter 方法。attr_accessible 指定可通过批量分配设置的模型属性白名单,例如 new(attributes)、update_attributes(attributes) 或 attribute=(attributes)。这是从链接此处摘录的
attr_accessor
simply creates a getter-setter method for an attribute.attr_accessible specifies a white list of model attributes that can be set via mass-assignment, such as new(attributes), update_attributes(attributes), or attributes=(attributes). This has been excerpted from the link here