【问题标题】:RoR: undefined method new for #<Class>RoR:#<Class> 的未定义新方法
【发布时间】:2014-08-27 13:40:17
【问题描述】:

我正在处理 Rails 中的嵌套资源。我的用户有一个农场。

用户模型:

class User < ActiveRecord::Base

has_one :farm

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable, 
     :token_authenticatable, :confirmable, :lockable, :timeoutable


attr_accessible :email, :password, :password_confirmation, :remember_me, :username

end

农场管理员

 class Farm < ActiveRecord::Base

 belongs_to :user

 attr_accessible :name, :contact, :adress, :user_id
 end

我的农场迁移

class CreateFarms < ActiveRecord::Migration
def change
create_table :farms do |t|
  t.references :user
  t.string :name
  t.string :contact
  t.string :adress

  t.timestamps
end
end
end

我的路线.rb

 resources :users do
  resource :farm, path: "farm"
 end


 devise_for :users, :path => 'account

所以我认为我所有的参考和关联都可以。但是当我尝试创建一个新农场时,我得到了上述错误。我在 FarmsController 中的新方法:

def new

@farm = @user.farm.new

respond_to do |format|
  format.html # new.html.erb
  format.json { render json: @farm }
end
end

我还有设置为 before_filter 的 load_User 函数

def load_User
  @user = User.find(current_user)

end

我使用的显示功能也会发生同样的事情

@farm = @user.farm.find(params[:id])

它说没有“查找”方法。 如果有人可以提供帮助和/或详细说明,我无法猜测或找到原因。

【问题讨论】:

  • 我刚刚补充说它对“find”方法也是如此。
  • 你应该考虑在你的用户模型中删除这些attr_accessible(也可能是农场),因为它有点误导。
  • 任何答案对您有帮助吗?
  • 是的,谢谢。你的回答清除了很多其他相关的东西。

标签: ruby-on-rails ruby methods resources nested


【解决方案1】:

您遇到此错误是因为(可能)您尝试在 Farm 实例上调用 find,该实例没有定义 find 方法。由于@user.farm 已经返回Farm 实例(或nil),您应该简单地:

@farm = @user.farm

您的第一个错误与此类似。这是因为没有为Farm 实例定义new 方法。相反,您应该:

@farm = @user.build_farm

【讨论】:

    【解决方案2】:
    1. 没有@user.farm.new 方法,因为它是一对一的关联。试试@user.build_farm

    2. 真的很简单。如果只有一个农场,则无需搜索。 @user.farm 应该够了。

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多