QQCode
QQCode

Reputation: 5

Ruby on Rails - Creating a database table within different class

so I am new to RoR and am not sure what the proper method is for what I am trying to do. So this is what I have:

class Artist < ActiveRecord:Base

  def self.search(search)
      Artist.create(:artist_name => x, artist_info => ... etc)

I've shortened it for simplicity but you get the point. Now I have another model called "Album". I want to create an Album database entry along side the artist one but I simply create it as Albums.create(...) obviously because I am not within the Albums class. Would it be possible to call a function within the Albums class within my search method in Artist?

Something like:

class Artist < ActiveRecord:Base

      def self.search(search)
          Artist.create(:artist_name => x, artist_info => ... etc)
          Albums.method(search)

Class Album < ActiveRecord:Base
      def self.method(search)
           etc

Upvotes: 0

Views: 150

Answers (2)

tadman
tadman

Reputation: 211600

The Rails way of doing this is to set up your relationships and use those to create associated records:

class Artist
  has_many :albums
end

class Album
  belongs_to :artist
end

When creating your artist, if you want to create both:

Artist.transaction do
  artist = Artist.create!(
    artist_name: x,
    artist_info: y
  )

  album = artist.albums.create!(...)
end

You generally want to do that inside a transaction to avoid cluttering up the method with half-finished records if there's an error.

I'm not sure why you're using method here, that's not something you should use as a name, it's reserved by Ruby. That doesn't actually call the method, it just returns information about it.

There's no reason why one class can't call methods on another so long as they're not private or protected. Sometimes it's just not a good idea since there's a better way.

Upvotes: 1

QQCode
QQCode

Reputation: 5

I actually found the answer. For anyone searching for the same question, you can call other methods by "class".method. So in my case it would be Album.method(search)

Upvotes: 0

Related Questions