1

我正在尝试了解 Rails 3 中的新 arel 引擎,但我有一个问题。

我有两个模型,用户和任务

class User < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :user
end

这是我暗示这种关系的路线:

resources :users do
  resources :tasks
end

这是我的任务控制器:

class TasksController < ApplicationController
  before_filter :load_user

  def new
    @task = @user.tasks.new
  end

  private

  def load_user
    @user = User.where(:id => params[:user_id])
  end
end

问题是,当我尝试调用新操作时出现以下错误:

NoMethodError: undefined method `tasks' for #<ActiveRecord::Relation:0x3dc2488>

我确定我的问题出在新的 arel 引擎上,有人知道我做错了什么吗?

对不起,这是我的 schema.db 文件:

ActiveRecord::Schema.define(:version => 20100525021007) do

create_table "tasks", :force => true do |t|
  t.string   "name"
  t.integer  "estimated_time"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.integer  "user_id"
end

create_table "users", :force => true do |t|
  t.string   "email",                               :default => "", :null => false
  t.string   "encrypted_password",   :limit => 128, :default => "", :null => false
  t.string   "password_salt",                       :default => "", :null => false
  t.string   "reset_password_token"
  t.string   "remember_token"
  t.datetime "remember_created_at"
  t.integer  "sign_in_count",                       :default => 0
  t.datetime "current_sign_in_at"
  t.datetime "last_sign_in_at"
  t.string   "current_sign_in_ip"
  t.string   "last_sign_in_ip"
  t.datetime "created_at"
  t.datetime "updated_at"
  t.string   "username"
end

add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["reset_password_token"], :name =>       "index_users_on_reset_password_token", :unique => true
add_index "users", ["username"], :name => "index_users_on_username", :unique => true

end
4

4 回答 4

2

我相信你想要:

def load_user
  @user = User.where(:id => params[:user_id]).first
end

在您要求记录之前,它将保持关系。


find(params[:user_id])仍将工作并返回记录。

于 2010-05-28T15:47:53.597 回答
1

如果你改变你的load_user方法,它会起作用吗?

def load_user
  @user = User.find(params[:user_id])
end

另外,我认为您可能需要将new操作更改为:

def new
  @task = @user.tasks.build
end
于 2010-05-28T15:45:54.350 回答
0

不要将 Arel gem 的界面与新的 ActiveRecord 查询界面混淆。此处描述的语法不起作用:http: //github.com/brynary/arel

ActiveRecord 在底层使用 Arel,但创建了自己的类似 Arel 的 API。下面简单介绍一下新的 ActiveRecord 查询接口: http: //m.onkey.org/2010/1/22/active-record-query-interface

于 2010-05-29T03:24:47.660 回答
0

其实很简单。这是一种方法...

  def new
    @task = @user.tasks.new 
  end

  private

  def load_user
    # you must call a non-deferred operator to actually return 
    # the tuple that is connected to your tasks
    @user = User.where(:id => params[:user_id]).first
  end

一定要看看我正在做的关于主动关系的七部分学习系列。第一集将帮助您更清楚地了解您的错误。 http://Innovative-Studios.com/#pilot

如前所述,在某些情况下不推荐使用 find()。我会限制将 find() 用于原子值(您正在搜索特定项目/索引的位置)任何可能基于集合的东西我都会坚持使用 ActiveRecord for Arel 中的 Where(限制)子句包装器。

于 2010-05-30T13:56:52.027 回答