通过外键将关联的模型数据与RoR中的模型相结合



我有两个模型,Tweets和TweetsLocations,它们彼此关联:

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

和:

class TweetsLocation < ActiveRecord::Base
  belongs_to :tweet

如果我加载一个Tweet,比如@tweet = Tweet.find(1),我可以毫无问题地看到它的所有属性。如果我想查看关联的Location属性,我可以使用@tweet.location,同样没有问题。

但是,如果我想拥有一个由所有@tweet组成的JSON数组,其中包括Locations中的相关属性,这是可能的吗?还是我需要创建一个新的"tweets_with_Locations"数组,其中内置Locations模型中的tweet和属性?

如果您只想在JSON输出中包含TweetsLocation对象,您可以使用:include选项来as_json,例如:

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

然而,如果你想把TweetsLocation的属性当作Tweet本身的属性来包含,那就有点复杂了,但你有几个选项:

首先,您可以将所需的属性委托给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密钥。

其次,您可以覆盖as_json,以任何方式对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

最新更新