【问题标题】:Rails associations has_many and belongs_to not workingRails 关联 has_many 和 belongs_to 不起作用
【发布时间】:2017-10-26 16:35:35
【问题描述】:

ProposalsController#index 中的参数错误

找不到名称“clients”的关联。已经定义了吗?

我在我的应用程序上遇到了这个错误。找不到解决方案来解决它。有什么想法吗?

这里是模态:

class Client < ActiveRecord::Base
  has_paper_trail
   
  has_many :documents
  
  accepts_nested_attributes_for :documents, allow_destroy: true, reject_if: :all_blank
  
end

class Document < ActiveRecord::Base
  has_paper_trail
  
  belongs_to :client
  
  accepts_nested_attributes_for :clients, allow_destroy: true, reject_if: :all_blank
  
  validates :name, presence: true 
end

这里是文档的控制器:

  def index
    if current_user.admin?
      @documents = Document.paginate(page: params[:page], :per_page => 20) 
    else
      @documents = Document.where("user_id = ?", current_user).paginate(page: params[:page], :per_page => 20)
    end
  end
  1. 我已将“client_id”放入文档数据库中。
  2. 我已将所有安全参数放入两个控制器中。

【问题讨论】:

  • 你能把ProposalsController#index的代码包含进来吗?请注意,根据您的定义,您可以调用document.client,但不能调用document.clients
  • @Julie 刚刚添加。但是如果尝试 /documents/new 错误不是 ProposalsController#new。它发生在控制器中的每个方法上。

标签: ruby-on-rails nested associations model-associations


【解决方案1】:

你快到了,只是错过了一个小细节。始终遵循解释器/编译器所说的内容,您可以找到问题所在。

在你的情况下,:clientsaccepts_nested_attributes_for 中应该是单数,因为它是一个belongs_to

class Document < ActiveRecord::Base
  has_paper_trail

  belongs_to :client

  accepts_nested_attributes_for :client, allow_destroy: true, reject_if: :all_blank

  validates :name, presence: true 
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多