简单关联在控制台中工作但不在应用程序中

时间:2016-09-09 14:12:38

标签: ruby-on-rails

我正在尝试使用一个简单的关联来显示user.email的工作流程。

 def mail_notify_engineering
    @workflow = Workflow.where("Title like ?", "Engineer")
    @workflow = @workflow.first
    $temp1 = @workflow
    $temp2 = @workflow.user.email

当我跑步时,我得到了

NoMethodError in ApplicationController#notify_engineering
undefined method `email' for #<Workflow:0xb1ba8b8>

Rails.root: C:/Users/cmendla/RubymineProjects/product_development

Application Trace | Framework Trace | Full Trace
app/mailers/application_mailer.rb:37:in `mail_notify_engineering'
app/controllers/application_controller.rb:19:in `notify_engineering'
Request

Parameters:

None

但是,如果我在控制台中运行命令,它似乎工作。

>> @workflow = Workflow.where("Title like ?", "Engineer")
  Workflow Load (3.0ms)  EXEC sp_executesql N'SELECT [pd].[workflows].* FROM [pd].[workflows] WHERE (Title like N''Engineer'')'
#<ActiveRecord::Relation [#<Workflow id: 3, title: "Engineer", user_id: 1, created_at: "2016-09-02 18:28:29", updated_at: "2016-09-02 18:28:29">]>
>> @workflow = @workflow.first
#<Workflow id: 3, title: "Engineer", user_id: 1, created_at: "2016-09-02 18:28:29", updated_at: "2016-09-02 18:28:29">
>> $temp2 = @workflow.user.email
"christopher.mendla@ccttapes.com"
  User Load (2.0ms)  EXEC sp_executesql N'SELECT  [pd].[users].* FROM [pd].[users] WHERE [pd].[users].[id] = @0  ORDER BY [pd].[users].[id] ASC OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY', N'@0 int', @0 = 1  [["id", 1]]

这两个模型是:

class Workflow < ActiveRecord::Base
  belongs_to :user, :class_name => 'Workflow', foreign_key: 'user_id'

  validates_presence_of :title
  validates_presence_of :user_id

  validates_uniqueness_of :title, :scope => :user_id

end



class User < ActiveRecord::Base
  has_many :workflows

表格是

TABLE pd.workflows ( 
    id INT IDENTITY NOT NULL, 
    title NVARCHAR(4000) NULL, 
    [user_id] INT NULL, 
    created_at DATETIME NOT NULL, 
    updated_at DATETIME NOT NULL, 
    CONSTRAINT PK__workflow__3213E83FA1246A13 PRIMARY KEY (id)
)


TABLE tl.users ( 
    id INT IDENTITY NOT NULL, 
    login VARCHAR(50) NULL, 
    group_strings TEXT NULL, 
    name VARCHAR(50) NULL, 
    ou_strings VARCHAR(150) NULL, 
    created_at DATETIME NOT NULL, 
    updated_at DATETIME NOT NULL, 
    email VARCHAR(50) NULL, 
    signature TEXT NULL, 
    operating_system VARCHAR(50) NULL, 
    notes_path VARCHAR(50) NULL, 
    client VARCHAR(50) NULL, 
    outlook_path VARCHAR(150) NULL, 
    CONSTRAINT PK_users PRIMARY KEY (id)
)

如果关联在控制台中运行,为什么它在作为应用程序运行时不起作用?

1 个答案:

答案 0 :(得分:1)

你是self_referencingWorkflow模型,所以

@workflow = Workflow.first
@workflow.user

会使Workflow

返回id = @workflow.user_id

将关联更改为

class Workflow < ActiveRecord::Base
  belongs_to :user
end

Rails会自动搜索user_id

中的Workflow