Rails: difference between attr_accessor and attr_accessible
What is the difference? Also, why does this not work:
The variables such as base_path are not being set.
cla开发者_JS百科ss 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?
attr_accessor
creates the getter method.attribute
and setter method.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:
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/"
Are you sure that you properly instantiated your class?
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
精彩评论