【问题标题】:edit and update function in controller for has_one active record associationhas_one 活动记录关联的控制器中的编辑和更新功能
【发布时间】:2018-06-20 07:59:22
【问题描述】:

我试图更好地了解如何正确调用 has_one 关系的更新操作。我收到以下错误

NameError(未初始化的常量 User::Companyinfos):app/controllers/companyinfos_controller.rb:3:in `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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    has_one 关系应该是 companyinfo 而不是 companyinfosphotos 模型也是如此,要了解 Rails 中的模型关联,this 应该是一个很好的起点

    【讨论】:

    • 是的,这行得通。我之前没有注意到这一点。使用 has_one 时,它​​是单数的,所以最后没有 s。谢谢!
    • 很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2016-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多