【问题标题】:using nested attributes in rails with cocoon在带有茧的rails中使用嵌套属性
【发布时间】:2018-08-08 00:12:55
【问题描述】:

我有这个设置,但由于某种原因,我无法将employent_history 保存在数据库中。当更新时仅更新配置文件属性,我使用了茧宝石

class User < ApplicationRecord
  has_one :profile, dependent: :destroy
  has_many :employent_histories :through :profile
  after_create :init_profile

  def init_profile
    self.create_profile!
  end
end

如您所见,配置文件是在创建新用户时创建的

我添加了另一个模型,称为就业历史,但属于用户和个人资料

配置文件模型 accept_nested_attributes_for :employment_history

class Profile < ApplicationRecord
  belongs_to :user
  has_many :employent_histories
  accepts_nested_attributes_for :employent_histories
end

class EmploymentHistory < ApplicationRecord
  belongs_to :user 
  belongs_to :profile

 end

profile_controller.rb

没有创建操作,因为资源是在处理新用户时创建的

class ProfilesController < ApplicationController

  def show
    @profile = current_user.profile
  end


  def edit
      @profile = current_user.profile
  end


    def update
    # byebug
      @profile = current_user.profile
    respond_to do |format|
      if @profile.update profile_params
        format.html { redirect_to user_profile_path, notice: "Profile updated!" }
        format.json { render :edit, status: :ok, location: @profile }
      else
        format.html { redirect_to edit_user_profile_path, flash: { error: "Profile could not be updated!" } }
        format.json { render json: @profile.errors.messages, status: :unprocessable_entity }
      end
    end
  end

  private
  def profile_params
    params.require(:profile).permit(:title,:phone,:address,:zip_code,employment_histories:[:job_title,:employer,:_destroy])
  end

views/profiles/edit.html.erb

<%= form_for @profile, url: {action: "update"} do |f| %>
   <%= attributes%>
   <%= attributes%>
     <%= f.fields_for :employment_histories do |ff| %>
      <%= attributes%>
     <%end%>
<%f.sumbit%>
<%end%>

使用此设置,嵌套属性表单的字段不会显示在编辑配置文件页面上。 我错过了什么

【问题讨论】:

  • 您的代码有很多语法错误和格式错误。你能解决这些问题吗?
  • 如果您“想将nested_attributes 参数添加到配置文件创建中”,为什么不这样做self.create_profile!(employment_histories_attributes: [{ &lt;obj1-attributes&gt; }, { &lt;obj2-attributes&gt; }])
  • 你从哪里得到这些属性的值?
  • 我编辑了这个问题,因为我遇到了嵌套表单的问题
  • 你有什么问题?

标签: ruby-on-rails ruby nested-attributes


【解决方案1】:

您在参数中允许:employment_histories,但AFAIR,嵌套参数应该在键:&lt;association-name&gt;_attributes 下接收。

此外,您应该允许嵌套对象的id,以防您想再次编辑它们。

所以,最终的profile_params 应该是这样的:

def profile_params
  params.require(:profile)
        .permit(
          :title,
          :phone,
          :address,
          :zip_code,
          employment_histories_attributes: [:id, :job_title, :employer, :_destroy]
        )
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 1970-01-01
    相关资源
    最近更新 更多