Hi
I have a controller open_service_desk and create action .Inside the
action when create a ticket I need to get default values of some fields
from a yml file say get_value.yml In that file I am storing values
like ..(I dont know whether this the right way)..Why I am storing this
is these are mandatory fields and I have set validation also these are
not get from the user directly.
Assuming that your yaml file is in test/fixtures directory. Do
something like this
#say ticket is an object going to be created
yml=File.open("#{RAILS_ROOT}/test/fixture/get_value.yml){|ym|
YAML::load(ym) }
ticket.service_desk_status_id=yml["sd"]
["service_desk_status_id"].to_i #assuming it to be integer
ticket.service_desk_category_id=yml["sd"]
["service_desk_category_id"].to_i
ticket.service_desk_sub_category_id=yml["sd"]
["service_desk_sub_category_id"].to_i
I was going to take a different tack. Assuming this isn't a test
fixture
but just a file that is being used from somewhere to set default
values
for new objects, then you could do:
There are probably other ways to set defaults rather than loading up a
file like this though.
You could embed them in a class method in the model and just pull them
out when you
need them. Or maybe apply them in a callback (http://
api.rubyonrails.org/classes/ActiveRecord/Callbacks.html) like
before_create. Or use :default in your migration when defining the
table - might not be appropriate doing this with id's though.
Callback example:
class Foo < ActiveRecord::Base
before_create :apply_defaults
private
def apply_defaults
self.field1='val1' if self.field1.blank?
end
end
Hi
Thanks for the reply.May I ask one more question? As Daniel Bush said
this isn't a test fixture but just a file that is being used to set
default values..So my question normally in which directory I can store
this yml file whether inside models or view or anywhere?
You can store it anywhere you want really (although I'd just stick
with letting the database handle default values)
I can't see the reason for using yaml like this - but I guess you have
your reasons.
Since you're set on having your controller load up a yaml file every
time it's accessed then I'd probably stick it in db/ somewhere. As
Fred says, you could put it anywhere.
You could lazy load it to save hitting the file system every time:
class YourModel < ActiveRecord::Base
def YourModel.default_values
@@default_values ||= YAML.load_file(RAILS_ROOT+'/db/
get_value.yml')
end
end