Rails ActiveRecord define database objects within other object -



Rails ActiveRecord define database objects within other object -

i'm relatively new rails , new database manipulation.

i'm trying create class within database contains number of custom objects within it. these custom objects stored in database in separate table. i've managed set follows

class myclass < activerecord::base has_many :other_objects, :dependent => destroy end class otherobject < activerecord::base belongs_to :my_class attr_accessible :some_stuff... end

i've created appropriate database tables , managed working.

now want have (four) particular instances of "otherobject"s in class, can accessed straightforward identifier,

test = myclass.new ... test.instance_of_other_object.some_attribute = "blahblah"

such updates database entry associated object. best way go this?

that has_many association sets myclass#other_objects (and a bunch of other methods) allow work associated records.

you want:

my_class.other_objects.each |other_object| other_object.update_attributes(:foo => 'bar') end

if want direct sql update, can utilize update_all:

my_class.other_objects.update_all(:foo => 'bar')

update:

if that's sort of association need, may define belongs_to association:

class myclass < activerecord::base has_many :other_objects, :dependent => :destroy # uses :selected_other_object_id belongs_to :selected_other_object, :class_name => "otherobject" end my_class = myclass.first my_class.selected_other_object = other_object # set object. # => #<otherclass:...> my_class.selected_other_object_id # id has been set. # => 10 my_class.selected_other_object # retrieve object. # => #<otherclass:...> my_class.selected_other_object.save # persist id , other fields in db. my_class = myclass.find(my_class.id) # if fetch object again... # => #<myclass:...> my_class.selected_other_object_id # id still there. # => 10 my_class.selected_other_object # have id, object. # => #<otherclass:...> my_class.selected_other_object.foo = "bar" # access associated object way. another_variable = my_class.selected_other_object # or way.

remember not assume :selected_other_object subset of :other_objects.

also note selected_other_object , selected_other_object= methods set when set association, don't have define these yourself.

ruby-on-rails-3 activerecord

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -