为什么我会得到这个NoMethodError

时间:2013-04-29 22:10:28

标签: ruby-on-rails

我正在制作一个Twitter副本,现在我正在尝试显示其他用户正在关注的用户的所有帖子。我是ruby和rails的新手,所以我可能会这样做很奇怪..

这些是我的文件:

会话#home.html.erb

<h2 class='User_Header'> Home <h2>

<%= link_to "New Post", controller: "posts", action: "new" %>
<%= link_to "Log Out", :controller => "sessions", :action => "logout" %>
<%= show_tweets("following") %>

sessions_helper

module SessionsHelper

    def show_tweets(opt)
        if opt == "following"
            @sub = Subscription.where("userID = ?", @current_user.id)
            @post = Post.where("user_id = ?", @sub.followingID)

            render partial: 'shared/follower_tweets'
        end
    end

    def show_tweet(s)
        @post = Post.where("user_id = ?", s.id)
        render partial: 'shared/tweet'
    end

    def tweet_username(p)
        @username = User.where("id = ?", p.user_id) 
        Rails.logger.debug @username.inspect
        render partial: 'shared/user'
    end
end

_follower_tweets.html.erb

<h2>Tweets</h2>

<table>
    <tr>
        <th>Username</th>
        <th>Tweet</th>
    </tr>

    <% div_for(@post, class: 'post') do %>
        <td><%= tweet_username(@post) %></td>
        <td><%= @post.content %></td>
    <% end %>
</table>

_user.html.erb

<%= @username %>

session.rb

class Session < ActiveRecord::Base  
    attr_accessible :content, :user_id, :followingID, :userID
end

错误

app / views / sessions / home.html.erb第9行引出:

undefined method `followingID' for #<ActiveRecord::Relation:0x007fd74b66f8a8>

2 个答案:

答案 0 :(得分:0)

检查您的模型的关联是否正确。消息表明有关于此的错误。

答案 1 :(得分:0)

发生的情况是,followingID模型上的Session代替Subscription模型。应该类似于以下内容:

class Subscription < ActiveRecord::Base  
  attr_accessible :followingID
end

然而,问题比那更重要。您必须阅读Active Record Associations,然后才能执行类似

的操作
@subs = @current_user.subscriptions
@posts = @current_user.posts