我正在努力更好地了解如何正确调用has_one
关系的更新操作。我收到以下错误
NameError(未初始化的常量User :: Companyinfos):app / controllers / companyinfos_controller.rb:3:在`edit'
我想帮助修复我的控制器,但是在数据库中使用关联时,还有一篇很好的文章来阅读控制器。我是新人,并试图变得更好。
user.rb
class User < ApplicationRecord
enum role: [:startup, :investor]
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :photos, dependent: :destroy
has_one :companyinfos, dependent: :destroy
validates :name, presence: true
validates :role, presence: true
after_create :add_companyinfos
def add_companyinfos
Companyinfo.create(user: self)
end
端
我正在使用after_create因为我只希望用户能够编辑公司信息。
companyinfo.rb
class Companyinfo < ApplicationRecord
belongs_to :user
end
companyinfos_controller.rb
class CompanyinfosController < ApplicationController
def edit
@companyinfo = User.find(current_user.id).companyinfos
end
def update
@companyinfo = Companyinfo.find(current_user.id).companyinfos
if @companyinfo.update(companyinfo_params)
flash[:notice] = "Saved ..."
else
flash[:alert] = "cannot save"
end
render 'edit'
end
private
def companyinfo_params
params.require(:company_basic).permit(:CompanyStage)
end
end
edit.html.erb
<%= form_for :companyinfo do |f| %>
<%= f.text_field :CompanyStage %>
<%= f.submit "save", class: "btn btn-success" %>
<% end %>
的routes.rb
resources :users, only: [:show] do
resources :photos, only: [:create, :destroy]
resources :companyinfos, only: [:edit, :update]
end
答案 0 :(得分:0)
has_one
关系应为companyinfo
而不是companyinfos
,photos
模式相同,要了解有关铁路中的模型关联,this应该是一个好的关系开始的地方