【问题标题】:rails 4 create new model object from associationrails 4 从关联创建新模型对象
【发布时间】:2014-03-30 10:35:47
【问题描述】:

我正在使用 rails 4,我正在尝试创建一个具有关联的新模型对象,这是我的 db 文件

class CreateClients < ActiveRecord::Migration
  def change
    create_table :clients do |t|
      t.string :nume
      t.string :nrtel
      t.string :email
      t.string :datan
      t.string :var
      t.string :var1
      t.string :var2
      t.string :var3
      t.string :var4
      t.string :var5

      t.timestamps
    end
  end
end
class CreateProgs < ActiveRecord::Migration
  def change
    create_table :progs do |t|
      t.string :data
      t.string :descriere
      t.string :status
      t.string :var
      t.string :var1
      t.string :var2
      t.string :var3
      t.string :var4
      t.string :var5


      t.timestamps
    end
  end
end
class AddClientidToProgs < ActiveRecord::Migration
  def change
    add_column :progs, :clientid, :integer
  end
end

在 progs 控制器中,新方法看起来像这样

def new
    #@client = Client.find(params[:client_id])
    c = Client.new
    @prog = c.progs.build

  end

我得到这个错误:

未知属性:client_id

提取的源代码(第 19 行附近): 17 18 19 20 21 22

#@client = Client.find(params[:client_id])
c = Client.new
@prog = c.progs.build

结束

Rails.root: /home/salon

应用程序跟踪 |框架跟踪 |全跟踪 app/controllers/progs_controller.rb:19:in `new' 请求

参数:

{"client_id"=>"1"}

谁能指出我正确的方向?

【问题讨论】:

    标签: object activerecord ruby-on-rails-4 model-associations


    【解决方案1】:

    首先应该设置clientprogs之间的关联。

    class AddClientidToProgs < ActiveRecord::Migration 
       def change add_column :progs, :client_id, :integer 
       end 
    end
    

    你写错了“clientid”。

    第二件事是联想应该是这样的

    client class
        has_many :progs
    
    prog class
       belongs_to client
    

    最后:

    @client = Client.find(params[:client_id])
    prog = @client.progs.build # or @client.progs.new
    

    以上命令将在prog 对象中设置client_id

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多