【问题标题】:Accessing nested models from other controllers从其他控制器访问嵌套模型
【发布时间】:2012-11-28 15:33:00
【问题描述】:

我有一个模型:

用户有_许多食谱,食谱属于_用户

recipe has_many cmets, comment belongs_to recipe

我的食谱嵌套在 cmets 中,我可以毫无问题地访问 Recipes_controller 上的 cmets。

如果我尝试从用户访问它,我得到未定义的方法错误。

我的 users_controller:

@user = User.find(params[:id])
@recipes = @user.recipes.paginate(page: param[:page])
@comments = @user.recipes.comments

如何从用户访问 cmets?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    @user.recipes 是该用户的所有食谱的数组。你必须选择一个特定的来调用“cmets”。像

    @user.recipes.first.comments
    

    【讨论】:

    • 在我的 cmets 中,我有一个评级,我想对用户拥有的所有食谱的 cmets 进行平均。有没有办法做到这一点?我在食谱中使用
    • 看看这个问题的答案 - stackoverflow.com/questions/1341271/average-from-a-ruby-array。您需要从中推断,因为您实际上是在对嵌套数组中的值进行平均,并且您正在尝试平均“comment.rating”而不仅仅是整数,但这应该会给您一个良好的开端。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多