Rails,Unknown key(s):client_id,在belongs_to关联中

时间:2011-04-21 10:01:30

标签: ruby-on-rails associations

我一直在寻找一段时间,但谷歌并没有真正帮助我。 ArgumentError Unknown key(s): client_id出现在ProjectsController中:

# projects_controller.rb

class Management::ProjectsController < Management::ManagementController
  def index
    @projects = Project.find( :client_id => current_user.client )
  end
end

这是项目模型:

# project.rb

class Project < ActiveRecord::Base
  belongs_to :client
end

这是客户端模型:

# client.rb

class Client < ActiveRecord::Base
  has_many :projects
end

最后,迁移:

# 20110404155917_create_projects.rb

class CreateProjects < ActiveRecord::Migration
  def self.up
    create_table :projects do |t|
      t.string :name
      t.datetime :date
      t.text :description
      t.integer :client_id
      t.timestamps
    end
  end

  def self.down
    drop_table :projects
  end
end

应该可以,对吧?

看不到我在这里缺少的东西..

有人有建议吗?

谢谢!

2 个答案:

答案 0 :(得分:5)

使用

@projects = Project.where( :client_id => current_user.client.id)

@projects = Project.find_by_client_id(current_user.client.id)

答案 1 :(得分:0)

或者你可以做到

@projects = current_user.client.projects

或许有点清洁?