将rails关联从has_many更改为has_one

时间:2018-11-25 19:00:51

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

我正在尝试将模型关联从has_many(有效)更改为has_one,但是遇到了问题。

当我去:

localhost:3000/users/1/security_badge/new

我在日志中得到了

NoMethodError (undefined method `new' for nil:NilClass):

用户模型:

class User < ApplicationRecord
  has_one :security_badge, dependent: :destroy
end

SecurityBadge模型:

class SecurityBadge < ApplicationRecord    
  belongs_to :user    
end

我的路线:

  resources :users do
    resource :security_badge
  end

我的某些控制器security_badges_controller:

  before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
  before_action :set_security_badge, only: [:show, :edit, :update, :destroy]

  def new
    @security_badge = @user.security_badge.new
  end

  def edit
  end

  def create
    @security_badge = @user.security_badge.new(security_badge_params)

    respond_to do |format|
      if @security_badge.save
        format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_user
      @user = User.find(params[:user_id])
    end

    def set_security_badge
      @security_badge = SecurityBadge.find(params[:id])
    end

更新

这是我的_form:

<%= form_with(model: [@user, security_badge], local: true) do |form| %>
  <% if security_badge.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>

      <ul>
      <% security_badge.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :name %>
    <%= form.text_field :name, autofocus:true, class: "form-control" %>
  </div>

  <br>
  <div class="row float-right">
    <div class="col-md-12 actions">
        <%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
        <%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
    </div>
  </div>

<% end %>

新视图模板:

<%= render 'form', security_badge: @security_badge %>

1 个答案:

答案 0 :(得分:3)

使用var eng; var fr; $("document").ready(function () { $.getJSON("French.json").done(function (french) { fr = french; }); $.getJSON("english.json").done(function (english) { eng = english; }); }); (由var lang; $("document").ready(function () { toggle = function (json) { $.getJSON(json).done(function (lang) { lang = french; }); } }); 关联宏提供的方法)而不是@user.build_security_badgehas_one为nil,这就是为什么会出错)。

https://guides.rubyonrails.org/association_basics.html#has-one-association-reference