【问题标题】:Issue with the build for has_one associationhas_one 关联的构建问题
【发布时间】:2020-11-12 18:17:10
【问题描述】:

每次我尝试使用 has_one 关联保存模型时都会收到错误消息,而且我不确定自己做错了什么。这是下面的错误信息和代码

用户.rb

  has_one :user_options

user_option.rb

 belongs_to(
        :user,
        class_name: 'User',
        foreign_key: 'user_id',
        inverse_of: :user_options
    )

user_options_controller.rb

def create
    @user = current_user
    @user_option = current_user.build_user_option(user_option_params)
    respond_to do |format|
      if @user_option.save
        format.html { redirect_to @user_option, notice: 'User option was successfully created.' }
        format.json { render :show, status: :created, location: @user_option }
      else
        format.html { render :new }
        format.json { render json: @user_option.errors, status: :unprocessable_entity }
      end
    end
  end

任何帮助都会很棒!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    改变

    has_one :user_options
    

    has_one :user_option
    

    根据 ruby​​ 约定,您应该为 has_oneplural 使用单数名称 has_many 关联。

    正如您为has_one 关系提供了user_options,用户模型的每个实例都可以访问build_user_options 而不是build_user_option Ref has-one-association-reference

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-09
      • 1970-01-01
      • 2017-11-12
      • 2011-04-19
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多