0

例如,如果我有 id 和 user_id 列,在名为“microposts”的模型/数据集/表(技术术语?)中,比较我可以使用的两组

Micropost.where("user_id = ?", id)

但是,我想知道如何对来自不同数据集/表/模型的数据做同样的事情。在这个特定的场景中,我试图找到用户的社区变量等于任何微帖子的社区变量的所有实例。我正在尝试匹配字符串的内容,以便呈现所有具有与当前用户的社区变量匹配的社区变量的微博。这些变量在用户和微博的模型/数据集/表中的“社区”列下以字符串形式为@city + @state。插图:

   users table                             microposts table
user_id   community              micropost_id   content    community
1          FairfieldIowa           1             blub!      FairfieldIowa
2          FairfieldIowa           2             Hiiy       FairfieldIowa
3          Salt Lake CityUtah      3             wwowt!     Salt Lake CityUtah
4          Salt Lake CityUtah      4             hey        Salt Lake CityUtah
5          FairfieldIowa           5             sweet      FairfieldIowa

我认为这可能适用于用户模型:

def communityfeed
      Micropost.where("community = ?", user.community)
    end

但是,我认为,由于语法、逻辑或“用户”并未定义所有用户,这是不正确的。

然后我在 pages_controller 中定义 communityfeed_items 为:

def home
    if logged_in?
      @micropost = current_user.microposts.build
      @communityfeed_items = communityfeed.paginate(page: params[:page])
  end
end

但我得到一个undefined local variable or method communityfeed错误

这可能是因为我没有提供任何用户使用该方法。也许简单地为所有用户使用一个变量就可以解决我的问题,但这是我找不到的。我已经尝试了 all_users 和 user,但没有成功。是否可以比较变量以以这种方式呈现结果,如果可以,循环遍历所有用户/微帖子并检查这些匹配项的语法是什么?

我还构建了几个局部函数来共同渲染微帖子,但是,如果 @communityfeed_items 变量没有正确运行,它们几乎没有用处。

_communityfeed.html.erb

<% if @communityfeed_items.any? %>
    <ol class="microposts">
        <%= render partial: 'shared/communityfeed_item', collection: @communityfeed_items %>
        </ol>
        <%= will_paginate @communityfeed_items %>
        <% end %>

_communityfeed_items.html.erb

<li id="<%= communityfeed_item.id %>">
    <%= link_to gravatar_for(communityfeed_item.user), communityfeed_item.user %>
     <span class="user">
        <%= link_to communityfeed_item.user.name, communityfeed_item.user %>
      </span>
      <span class="content"><%= communityfeed_item.content %></span>
      <span class="timestamp">
        Posted <%= time_ago_in_words(communityfeed_item.created_at) %> ago.
      </span>
    <% if current_user?(communityfeed_item.user) %>
        <%= link_to "delete", communityfeed_item, method:  :delete,
                                         confirm: "You sure?",
                                         title:   communityfeed_item.content %>
      <% end %>
    </li>

如果我以非常低效/不可能的方式解决了这个问题,我愿意接受建议。

感谢您的时间、慷慨和专业知识。

4

0 回答 0