activerecord - Rails 3: how to update has_one and has_many pointing to the same table at the same time -
activerecord - Rails 3: how to update has_one and has_many pointing to the same table at the same time -
thanks helping out noob. have next relationships in 2 models:
class reader < activerecord::base has_many :books, :dependent => :destroy has_one :last_book, :class_name => "book" end class book < activerecord::base belongs_to :reader end
i want last_book recent book associated reader.
right in book controller creating book follows similar code in update
def create @reader = reader.find(params[:reader_id]) @book = @reader.books.new (params[:book]) @reader.last_data = @book end
i think ends writing book twice database. there cleaner/more efficient way this?
has_one
allows :order
clause, this:
class reader < activerecord::base has_many :books, :dependent => :destroy has_one :last_book, :class_name => "book", :order => "books.created_at desc" end
then in controller action drop 1 of assignments
def create @reader = reader.find(params[:reader_id]) @book = @reader.books.new (params[:book]) end
jeff smith's reply correct.
ruby-on-rails-3 activerecord
Comments
Post a Comment