简体   繁体   English

如何在视图(角度)中显示关联的模型数据(来自Rails)

[英]How to show in view (Angular) associated model data (from Rails)

I have problem with expressions associated data. 我对与表达式相关的数据有疑问。 I have order and parent model meal . 我有秩序和父模型 Meal has one order. 一顿饭。 Order has: id of meal and status. 订单具有:用餐ID和状态。 order.status is display proper, but order.meal.name doesn't. order.status可以正确显示,但order.meal.name不能正确显示。 This is my rails controller: 这是我的rails控制器:

def index
  respond_with current_user.orders
end

In that way I try display data in Angular: 这样,我尝试在Angular中显示数据:

 <tbody ng-repeat="order in orders | orderBy: '-cost' | filter:activeOrder">
    <tr>
      <td>{{order.id}}</td>
      <td>{{order.meal.name}}</td>
      <td>{{order.meal.cost}}</td>
      <td>{{order.status}}</td>
    </tr>
  </tbody>
  </table>

Create order in Angular: 在Angular中创建订单:

orders.create({
  meal_id: $scope.meal.id,
  status: "ordered",
});

And create in Rails: 并在Rails中创建:

def create
    order = meal.create_order(order_params.merge(user_id: current_user.id))
    respond_with order
end

What can be wrong with this code? 此代码有什么问题?

 def index
  temp_array = Array.new
  current_user.orders.each do |order|
  temp_hash = Hash.new
  temp_hash[:order] = order
  temp_hash[:meal] = order.meal
  temp_array << temp_hash
  end

   respond_with temp_array.to_json
 end


<tbody ng-repeat="order in orders | orderBy: '-cost' | filter:activeOrder">
<tr>
  <td>{{order.order.id}}</td>
  <td>{{order.meal.name}}</td>
  <td>{{order.meal.cost}}</td>
  <td>{{order.status}}</td>
</tr>

Angular can can't access the model associations so you manually pass the value to show Angular无法访问模型关联,因此您手动传递值以显示

In Order model I've wrote this code: Order模型中,我编写了以下代码:

def as_json(options = {})
  super(options.merge(include: :meal))
end

And now it working! 现在就可以了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM