Site Archives associations

Generating association while generating model


May be you guys are already aware of, but in Rails 2.2 we can specify belongs_to association while generating model. So if we issue:

script/generate model Post title:string author:belongs_to

We will get a Post model like:

class Post < ActiveRecord::Base
belongs_to :author
end

Also it will automatically add the foreign key column in the migration.

class CreatePosts < ActiveRecord::Migration
[...]

When Ultrasphinx is used with polymorphic associations…


Lets first consider simple has_many and belongs_to associations as:

class Article < ActiveRecord::Base
has_many :comments
end

class Comment < ActiveRecord::Base
belongs_to :article
end

Now if you wish to index the title of associated article with comment for searching, you just need to add ” is_indexed :fields => :body, :include => [{ :association_name => 'article', :field => 'title', :as=> [...]