获取 rails 提供给 angular 的 json 中的关联 table 内容

Getting the associated table content inside the json given to angular by rails

我将 angular 与 rails 一起使用,其中我有一个 index.html.erb 页面,它点击了控制器操作

def index
@listings=Listing.all
end

/app.js/

var app = angular.module("PetForLife", ['ngResource']);

我正在通过 init 方法将这个@listings 传递给我的 angular 控制器。

现在的问题是此列表 table 与照片 table 相关联,照片 table 存储了与每个列表关联的多张照片,所以简而言之,我有

/Listing.rb/

class Listing < ActiveRecord::Base
    has_many :photos
end

/Photo.rb/

class Photo < ActiveRecord::Base
    mount_uploader :file_name, PhotoUploader
    belongs_to :listing
end

我的angular控制器代码是

/ListingController.js/

app.controller('ListingController', ['$scope', '$resource', function($scope, $resource) {
    $scope.post = "Angular Rocks!"

    $scope.init = function(listings)
    {
            $scope.listings = angular.fromJson(listings)

    }

    $scope.clear = function(){

        delete $scope.listing1.breed_type;

    }
    $scope.clearAll = function(){

        delete $scope.listing1;

    }

}]);

/index.html.erb/

<div ng-controller="ListingController">
<div class="ui divided items" ng-init="init(<%=@listings.to_json %>)">
  <div class="item" ng-repeat="listing in listings | filter:{'gender':listing1.gender,'pet_type':listing1.pet_type,'breed_type':listing1.breed_type}:true">

      <div class="image">

      </div>
      <div class="content listing_content">
        <i class="right floated large like icon"></i>
        <i class="right floated large star icon"></i>

        <%=link_to '{{listing.title}}','{{listing.id}}',class:'header'%>
        <div class="meta">
          <span class="cinema">Posted On
          <%@date = '{{listing.created_at}}'  %>
          </span>
        </div>
        <div class="description">
          {{listing.love_for_pets}}
        </div>


        <div class="extra listing_price">
          <div class="right floated ui circular facebook icon button">
            <i class="facebook icon"></i>
          </div>
          <div class="right floated ui circular twitter icon button">
            <i class="twitter icon"></i>
          </div>

          <div class="right floated ui circular google plus icon button">
            <i class="google plus icon"></i>
          </div>
          <div class="ui teal tag label"><i class="rupee icon"></i>{{listing.price}}</div>
        </div>
      </div>
    </div>


  </div>
  </div>

在index.html.erb文件中,

我想做这样的事情

<%=image_tag listing.photos.first.file_name.url%>

但是由于 angular 将此列表作为 json,因此找不到该关联。

我该如何实现。

通常你需要使用像@listings.to_json(:include => :photos)这样的东西 而不是 @listings.to_json 将关联包含到 json.