EzDevInfo.com

model interview questions

Top model frequently asked interview questions

Removing a model in rails (reverse of "rails g model Title...")

rails g model Rating user_id:integer message:string value:integer

How can I completely remove this model? Thanks


Source: (StackOverflow)

Rails "validates_uniqueness_of" Case Sensitivity

Here is the model (I am using SQLLite3):

class School < ActiveRecord::Base

  validates_uniqueness_of :name

end

For example, after I add "Yale", I cannot add "Yale" but can add "yale." How can I make the validation case insensitive?

EDIT: Found it - Active Record Validations


Source: (StackOverflow)

Advertisements

How to know whether a model is new or not?

class Post < ActiveRecord::Base
end

post = Post.new

How do I judge whether the 'post' is a new model which is not pulled from the database?


Source: (StackOverflow)

How should a model be structured in MVC?

I am just getting a grasp on the MVC framework and I often wonder how much code should go in the model. I tend to have a data access class that has methods like this:

public function CheckUsername($connection, $username)
{
    try
    {
        $data = array();
        $data['Username'] = $username;

        //// SQL
        $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE Username = :Username";

        //// Execute statement
        return $this->ExecuteObject($connection, $sql, $data);
    }
    catch(Exception $e)
    {
        throw $e;
    }
}

My models tend to be an entity class that is mapped to the database table.

Should the model object have all the database mapped properties as well as the code above or is it OK to separate that code out that actually does the database work?

Will I end up having four layers?


Source: (StackOverflow)

Doctrine2: Best way to handle many-to-many with extra columns in reference table

I'm wondering what's the best, the cleanest and the most simply way to work with many-to-many relations in Doctrine2.

Let's assume that we've got an album like Master of Puppets by Metallica with several tracks. But please note the fact that one track might appears in more that one album, like Battery by Metallica does - three albums are featuring this track.

So what I need is many-to-many relationship between albums and tracks, using third table with some additional columns (like position of the track in specified album). Actually I have to use, as Doctrine's documentation suggests, a double one-to-many relation to achieve that functionality.

/** @Entity() */
class Album {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column() */
    protected $title;

    /** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="album") */
    protected $tracklist;

    public function __construct() {
        $this->tracklist = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getTitle() {
        return $this->title;
    }

    public function getTracklist() {
        return $this->tracklist->toArray();
    }
}

/** @Entity() */
class Track {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column() */
    protected $title;

    /** @Column(type="time") */
    protected $duration;

    /** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="track") */
    protected $albumsFeaturingThisTrack; // btw: any idea how to name this relation? :)

    public function getTitle() {
        return $this->title;
    }

    public function getDuration() {
        return $this->duration;
    }
}

/** @Entity() */
class AlbumTrackReference {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @ManyToOne(targetEntity="Album", inversedBy="tracklist") */
    protected $album;

    /** @ManyToOne(targetEntity="Track", inversedBy="albumsFeaturingThisTrack") */
    protected $track;

    /** @Column(type="integer") */
    protected $position;

    /** @Column(type="boolean") */
    protected $isPromoted;

    public function getPosition() {
        return $this->position;
    }

    public function isPromoted() {
        return $this->isPromoted;
    }

    public function getAlbum() {
        return $this->album;
    }

    public function getTrack() {
        return $this->track;
    }
}

Sample data:

             Album
+----+--------------------------+
| id | title                    |
+----+--------------------------+
|  1 | Master of Puppets        |
|  2 | The Metallica Collection |
+----+--------------------------+

               Track
+----+----------------------+----------+
| id | title                | duration |
+----+----------------------+----------+
|  1 | Battery              | 00:05:13 |
|  2 | Nothing Else Matters | 00:06:29 |
|  3 | Damage Inc.          | 00:05:33 |
+----+----------------------+----------+

              AlbumTrackReference
+----+----------+----------+----------+------------+
| id | album_id | track_id | position | isPromoted |
+----+----------+----------+----------+------------+
|  1 |        1 |        2 |        2 |          1 |
|  2 |        1 |        3 |        1 |          0 |
|  3 |        1 |        1 |        3 |          0 |
|  4 |        2 |        2 |        1 |          0 |
+----+----------+----------+----------+------------+

Now I can display a list of albums and tracks associated to them:

$dql = '
    SELECT   a, tl, t
    FROM     Entity\Album a
    JOIN     a.tracklist tl
    JOIN     tl.track t
    ORDER BY tl.position ASC
';

$albums = $em->createQuery($dql)->getResult();

foreach ($albums as $album) {
    echo $album->getTitle() . PHP_EOL;

    foreach ($album->getTracklist() as $track) {
        echo sprintf("\t#%d - %-20s (%s) %s\n", 
            $track->getPosition(),
            $track->getTrack()->getTitle(),
            $track->getTrack()->getDuration()->format('H:i:s'),
            $track->isPromoted() ? ' - PROMOTED!' : ''
        );
    }   
}

The results are what I'm expecting, ie: a list of albums with their tracks in appropriate order and promoted ones being marked as promoted.

The Metallica Collection
    #1 - Nothing Else Matters (00:06:29) 
Master of Puppets
    #1 - Damage Inc.          (00:05:33) 
    #2 - Nothing Else Matters (00:06:29)  - PROMOTED!
    #3 - Battery              (00:05:13) 

So what's wrong?

This code demonstrates what's wrong:

foreach ($album->getTracklist() as $track) {
    echo $track->getTrack()->getTitle();
}

Album::getTracklist() returns an array of AlbumTrackReference objects instead of Track objects. I can't create proxy methods cause what if both, Album and Track would have getTitle() method? I could do some extra processing within Album::getTracklist() method but what's the most simply way to do that? Am I forced do write something like that?

public function getTracklist() {
    $tracklist = array();

    foreach ($this->tracklist as $key => $trackReference) {
        $tracklist[$key] = $trackReference->getTrack();

        $tracklist[$key]->setPosition($trackReference->getPosition());
        $tracklist[$key]->setPromoted($trackReference->isPromoted());
    }

    return $tracklist;
}

// And some extra getters/setters in Track class

EDIT

@beberlei suggested to use proxy methods:

class AlbumTrackReference {
    public function getTitle() {
        return $this->getTrack()->getTitle()
    }
}

That would be a good idea but I'm using that "reference object" from both sides: $album->getTracklist()[12]->getTitle() and $track->getAlbums()[1]->getTitle(), so getTitle() method should return different data based on the context of invocation.

I would have to do something like:

 getTracklist() {
     foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); }
 }

 // ....

 getAlbums() {
     foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); }
 }

 // ...

 AlbumTrackRef::getTitle() {
      return $this->{$this->context}->getTitle();
 }

And that's not a very clean way.


Source: (StackOverflow)

Default sort order for a rails model?

I would like to specify a default sort order in my model.

So that when I do a .where() without specifying an .order() it uses the default sort. But if I specify an .order(), it overrides the default.


Source: (StackOverflow)

Django required field in model form

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py

class CircuitForm(ModelForm):
    class Meta:
	    model = Circuit
	    exclude = ('lastPaged',)
    def __init__(self, *args, **kwargs):
	    super(CircuitForm, self).__init__(*args, **kwargs)
	    self.fields['begin'].widget = widgets.AdminSplitDateTime()
	    self.fields['end'].widget = widgets.AdminSplitDateTime()

In the actual Circuit model, the fields are defined like this:

begin = models.DateTimeField('Start Time', null=True, blank=True)
end = models.DateTimeField('Stop Time', null=True, blank=True)

My views.py for this is here:

def addCircuitForm(request):
    if request.method == 'POST':
	    form = CircuitForm(request.POST)
	    if form.is_valid():
		    form.save()
		    return HttpResponseRedirect('/sla/all')
    form = CircuitForm()	
    return render_to_response('sla/add.html', {'form': form})

What can I do so that the two fields aren't required?


Source: (StackOverflow)

Rails Model has_many with multiple foreign_keys

Relatively new to rails and trying to model a very simple family "tree" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten).

class Person < ActiveRecord::Base
  belongs_to :father, :class_name => 'Person'
  belongs_to :mother, :class_name => 'Person'
  has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
  has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end

Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether?

Thanks!


Source: (StackOverflow)

Magento - Passing data between a controller and a block

Really quick and simple question but I can't find a decent answer to this - What is the best way to pass data from a controller to a block in Magento.

Incase it makes a difference, I am loading the layout as follows:

 $this->loadLayout(array('default', 'myModule_default'));

    $this->_initLayoutMessages('customer/session')
         ->_initLayoutMessages('catalog/session')
         ->renderLayout();

I should add, that I have been using the registry as follows:

In the controller:

Mage::register('data', $data);

In the block:

$data = Mage::registry('data');

Not sure if this is the best way to do it though.


Source: (StackOverflow)

MVC: Data Models and View Models

I've read some MVC advice in the past regarding models stating that you should not reuse the same model objects for the domain and the view; but I haven't been able to find anyone willing to discuss why this is bad.

It is my opinion that creating two separate models - one for the domain, one for the view - and then mapping between them creates a lot of duplication, plus tedious mapping code (some of which might be alleviated by things like AutoMapper) that will likely be error prone.

What makes having a separate model for the two concerns worth the trouble of duplication and mapping code?


Source: (StackOverflow)

What is the Rails3 version of errors.add_to_base?

I want to write a custom validation in Rails 3, but following this example I get:

'ActiveModel::DeprecatedErrorMethods.add_to_base' call is deprecated in Rails 3.0

What is the rails3 version of:

def validate
   errors.add_to_base "If you are attaching a file you must enter a label for it" if !attachment.blank? and attachment_label.blank?
end

Source: (StackOverflow)

Ruby on Rails: errors.add_to_base vs. errors.add

I have read that errors.add_to_base should be used for errors associated with the object and not a specific attribute. I am having trouble conceptualizing what this means. Could someone provide an example of when I would want to use each?

For example, I have a Band model and each Band has a Genre. When I validate the presence of a genre, if the genre is missing should the error be added to the base?

The more examples the better

Thank you!


Source: (StackOverflow)

Rails :dependent => :destroy VS :dependent => :delete_all

In rails guides it's described like this:

Objects will be in addition destroyed if they’re associated with :dependent => :destroy, and deleted if they’re associated with :dependent => :delete_all

Right, cool. But what's the difference between being destroyed and being deleted? I tried both and it seems to do the same thing.


Source: (StackOverflow)

Rails model validation on create and update only

If I want to have validation only on create, then I can do

validates_presence_of :password, :on => :create

But how do I say on create and update? I tried this but it didn't work:

validates_presence_of :password, :on => [ :create, :update ]

Do I have to define the validation two times?


Source: (StackOverflow)

How to rename rails controller and model in a project

I started a Rails app and everything works fine. But now, I would like to remane a controller and the associated model:

I wanted to change the Corps controller to Stores and the same (without final s) for the model.

Looking on google, people suggested to destroy and then generate agin the controller and model. The problem is that it will erase the actual code of each files!

Any solution? Thanks in advance.


Source: (StackOverflow)