如何在轨道上的脚手架中检索模型数据?



已经一个星期了,我遇到了同样的问题,我找不到适合我问题的解决方案。我生成了一个名为Contracts的脚手架(reason:string,paf:string...(。然后我使用 rails g 模型生成了不同的表......地址、人员、个人等模型...所有这些表都引用了合同基架。我实际上可以使用<%= f.text_field :city %>在我的 _form.html.erb 中呈现这些字段(City 是位于地址模型中的字符串(。好的,一切似乎都正常工作。但是当我去显示.html.erb并做<p><%=@contract.address.city%></p>我得到noMethod错误"未定义的方法地址"然后我尝试<p><%=@address.city%></p>,我得到noMethod错误"nil:NilClass的未定义方法城市"我想这是控制器上的东西,但我试图添加。

def new @contract = Contract.new @address = Address.new end

我在节目控制器上做了同样的事情

def show @contract.find(params[id])@address.find(params[id] end

(我不确定语法是否正确,因为我做了 git 重置并且我不记得确切,这里的目的只是向你们展示我尝试过的内容。我知道这是错误的( 但不是成功。我看到人们为多个表生成各种脚手架,但 rails 社区说这不是一个好的做法。

或者也许有一种简单的方法来生成与我的脚手架相关的不同表?

我用同一个表中的所有数据做了同一个项目,但我的老板要求放入不同的表。

create_table "addresses", force: :cascade do |t|
t.string "estado"
t.string "cidade"
t.string "bairro"
t.string "endereco"
t.string "cep"
t.bigint "contrato_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["contrato_id"], name: "index_addresses_on_contrato_id"
create_table "contatos", force: :cascade do |t|
t.string "email"
t.string "phone"
t.bigint "contrato_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["contrato_id"], name: "index_contatos_on_contrato_id"

create_table "contratos", force: :cascade do |t|
t.string "razao"
t.string "cpnj"
t.string "insc_estadual"
t.string "insc_municipal"
t.string "paf"
t.string "empresa"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
add_foreign_key "addresses", "contratos"
add_foreign_key "contatos", "contratos"
add_foreign_key "data", "contratos"
add_foreign_key "responsavels", "contratos"

相反模型

class Contrato < ApplicationRecord
before_save do
self.paf.gsub!(/[[]"]/, "") if attribute_present?("paf")
end
end

您需要在合约模型上定义关联:

class Contrato < ApplicationRecord
has_one :address
# etc..
before_save do
self.paf.gsub!(/[[]"]/, "") if attribute_present?("paf")
end
end

这就是在模型中实际创建方法的原因。

查看指南以了解所有可用的关联:

https://guides.rubyonrails.org/association_basics.html#the-belongs-to-association

您尚未在Contrato模型中添加关联。如果你想像@contrato.address.city一样从contrato获取地址,你应该像下面这样添加

关联
class Contrato < ApplicationRecord
has_one :address
before_save do
self.paf.gsub!(/[[]"]/, "") if attribute_present?("paf")
end
end

对于视图城市,请对语法进行一些更改,例如@contrato&.address&.city

还要检查表中address条目,它是否包含您正在检查地址的合同 ID?

但是,我想知道你已经生成了一个像rails generate scaffold contract field1 field2...这样的脚手架,那么生成的模态应该是Contact而不是收缩。

最新更新