【问题标题】:RoR: nested attributes undefined method `buildRoR:嵌套属性未定义方法`build
【发布时间】:2015-06-26 18:45:11
【问题描述】:

我正在尝试在“客户”表单中放入一个嵌套的 fields_for 以同时添加他的地址。 关注了这个视频:https://www.youtube.com/watch?v=fsgTT9hizZo 这显示了我需要什么。

这是我的代码:

客户模型 =>

class Cliente < ActiveRecord::Base

 has_one :local
 accepts_nested_attributes_for :local


end

本地模型=>

class Local < ActiveRecord::Base
 belongs_to :cliente


end

客户端控制器 =>

def new
 @cliente = Cliente.new
 @cliente.build_local
end
def cliente_params
  params.require(:cliente).permit(:name, :telefone, :celular, :email, :local_attributes => [:logra, :cep, :uf, :city, :km])
end

客户视图

  <%= f.fields_for :local do |ff| %>

  <td>   <%= ff.text_field :km %> </td>

而且错误= 未定义的方法 `build_local' 用于# 在cliente_controller.rb中

【问题讨论】:

    标签: ruby-on-rails controller nested-attributes fields-for


    【解决方案1】:

    在创建local对象之前,首先需要创建cliente对象

    def new
      @cliente = Cliente.new      
    end
    
    def show
      @cliente = Cliente.find(params[:id])
      @cliente.build_local
    end
    

    【讨论】:

    • 它没有显示任何错误,但也没有在本地表中插入到
    【解决方案2】:

    试试看-

    @cliente.build_local()
    

    而不是-

    @cliente.build_local
    

    【讨论】:

    • 不知道为什么,但似乎模型工作不正常,我重新安装了所有东西,现在工作正常由于你的反应是现在的方式,我把它标记为正确。感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    相关资源
    最近更新 更多