Rails多对多关联

时间:2014-10-04 22:57:53

标签: ruby-on-rails ruby-on-rails-4 many-to-many

我已经为作业实现了一个保存按钮,现在工作正常我想在作业索引页面列出一些已保存的作业,我有这个代码

<h3>Saved Jobs</h3>
<ul>
<% @user.saved_jobs.limit(5).order(:created_at).reverse_order.each do |saved_job| %>
<li><%= link_to saved_job.job.title, saved_job.job.url %>
<span class="delete_button">    
<%= link_to "X", saved_job, :method => :delete, :remote => true %></span></li>
<% end %>
</ul>
<%= link_to "see all", saved_jobs_path %>

但是当我想访问作业索引页面时,我收到此错误undefined method saved_jobs' for nil:NilClass

这是我的saved_jobs控制器

class SavedJobsController < ApplicationController
    before_filter :authenticate_user!

    def index
        @saved_jobs = SavedJob.find_all_by_user_id(current_user.id) 
    end

    def create
        @job = Job.find(params[:saved_job][:job_id])
        current_user.save_job!(@job)

        respond_to do |format|
            format.html { redirect_to @job }
            format.js
        end
    end

    def destroy
        @job = SavedJob.find(params[:id]).job
        current_user.saved_jobs.find(params[:id]).destroy

        respond_to do |format|
            format.html { redirect_to @job }
            format.js
        end
    end

end

这是我的用户控制器

class ProfilesController < ApplicationController

  before_filter :authenticate_user!


  def show
    @user = User.find_by_slug(params[:id])
    if @user
      @posts = Post.all
      render action: :show
    else
      render file: 'public/404', status: 404, formats: [:html]
    end
  end


  def index
    @users = user_scope.paginate(page: params[:page], per_page: 2)
  end 

  private

  def user_scope
    current_user ? User.where.not(id: current_user.id) : User.all
  end

end

1 个答案:

答案 0 :(得分:0)

错误表明您没有在控制器操作中设置@user。你能从你的控制器发布代码吗?

根据控制器代码更新:

SavedJobsController中的索引操作未设置@user。然后在视图中调用@user.saved_jobs.limit(5)..etc... @user为nil,而不是current_user或其他。

此外,您已设置@saved_jobs - 为什么不使用它而不是@ user.saved_jobs?

例如:

#in SavedJobsController
def index
  @saved_jobs = current_user.saved_jobs.limit(5).order('created_at DESC')
end

然后,在您看来: <% @saved_jobs.each do |saved_job| %>