2012-01-15 4 views
0

でモデルと外部キーによって関連付けられたモデルデータを組み合わせる:私はツイートを読み込む場合と相互に関連し、私は2つのモデル、ツイートやTweetsLocationsを持つRoRの

class TweetsLocation < ActiveRecord::Base 
    belongs_to :tweet 

class Tweets < ActiveRecord::Base 
    has_one :location, :primary_key => "twitter_message_id", 
        :foreign_key => "twitter_message_id" 

そして、 、@tweet = Tweet.find(1)のように、私は問題のないすべての属性を見ることができます。関連する場所の属性を確認したい場合は、@tweet.locationで問題はありません。

しかし、Locationsの関連する属性を含むすべての@tweetのJSON配列を作成したい場合、これは優雅に可能ですか、またはつぶやきと一緒に "tweets_with_locations"の新しい配列を作成する必要がありますそれに私のLocationsモデルの属性が組み込まれていますか?

答えて

1

あなたはちょうどあなたが例えば、as_json:includeオプションを使用することができ、あなたのJSON出力にTweetsLocationオブジェクトを含める場合:

@tweet = Tweet.find 1 
@tweet.as_json :include => :location 

しかし、あなたは彼らがいたかのようにTweetsLocationの属性を含めたい、場合ツイート自体の属性、それはもう少し複雑だが、あなたはカップルのオプションがあります。

まず、あなたは例えば、TweetsLocationに必要な属性を委任することができます

class Tweets < ActiveRecord::Base 
    has_one :location, :primary_key => "twitter_message_id", 
        :foreign_key => "twitter_message_id" 

    # if TweetsLocation has e.g. "name" and "coordinates" attributes 
    delegate :coordinates, :name, :to => :location, :prefix => true 
end 

このようにして@tweet.as_jsonの出力はlocation_namelocation_coordinatesのキーになります。

第二に、あなたは例えば、あなたが好きなようにJSON出力をマッサージやってas_jsonをオーバーライドすることができます。:

class Tweets < ActiveRecord::Base 
    # ... 

    def as_json options = {} 
    # just merge all of TweetsLocation's attributes into the output 
    attributes.merge(location.attributes).to_json options 
    end 
end 
+0

パーフェクト、感謝ヨルダン – jbnunn

関連する問題