如何在控制器中使用current_user创建条件

时间:2013-09-12 16:53:50

标签: ruby-on-rails ruby rails-activerecord

我是一名新生,可以学习Rails并参与我的第一个有关在线图书写作的项目。

我已经制作了用户,书籍和版块的MVC。我想创建一个名为“作者地点”的按钮,它可以显示当前登录用户写的所有部分。

我想问一个简单的问题。如何使用当前用户名创建条件以从书籍数据库中选择当前作者的作品。我应该将此代码放在控制器或视图中吗?

代码如下。

ApplicationController的

current_user方法:

protect_from_forgery
helper_method :current_user

private
def current_user
  @current_user ||= User.find(session[:user_id]) if session[:user_id]
end

剖面模型:

class Section < ActiveRecord::Base
  attr_accessible :book_id, :section_content, :section_tag, :user_username
  belongs_to :book
  belongs_to :user
end

科控制器:

class SectionsController < ApplicationController
  def userpieces
    @sections=Section.find(:all, :conditions=>"user_username=current_user.username") # This part doesn't work
  end
end

或者以其他方式做任何建议?

2 个答案:

答案 0 :(得分:2)

假设您的has_many :sections模型中有相应的User关联,请尝试以下操作:

@sections = current_user.sections

答案 1 :(得分:0)

正如depa和izuriel所提到的,如果你的模型关系设置正确,你应该能够得到它。

无论如何,如果您希望以您尝试的方式获得它,请使用:

@sections=Section.find(:all, :conditions => ["user_username= ?",current_user.username])

请注意,在rails 3中,.find(:所有不推荐使用,请使用.all代替。