开发者

Add Model A's multiple columns to Model B's one column upon create, update

This is for a Rails question. Since my Thinking Sphinx somehow couldn't index the associate Model A, I am looking for a temporary solution.

Model A: -has columns: name, city

Model B: -has_many model A's -has column: country -I want to add a column called "tag" in Model B

Let's say we have:

B1 - United States of America (:country) and has A1 and A2 A1 - Walmart (:name), New York (:city) A2 - Starbucks (:name), San 开发者_开发技巧Francisco (:city)

Everytime when user creates/updates listing B1, the A.name and A.city: - each A mapped, added to the B.tag, join(', ') - then save

So in the above example, B1.tag will have: walmart, new york, starbucks, san francisco

So then I can put this in Model B:

class B < ActiveRecord::Base
  has_many :as      # plural for A's

# ThinkingSphinx Index
  define_index do
    indexes :country
    indexes :tag
  end

end

I haven't added the Tag column in my B yet.

How do I write this in my B controller so that everytime when it's created/saved, it will automatically mapped each A, then join(', ') the A.name and A.city into B.tag?

Sorry, I am just learning rails.

Thanks.


Use an observer (http://api.rubyonrails.org/classes/ActiveRecord/Observer.html) to run the code after_create on your A model. Then just locate the new values and add them to your B model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜