无法保存新的关联首选项has_one association

时间:2017-06-10 15:04:07

标签: ruby-on-rails

我尝试为has_one首选项创建一个嵌套模型表单。 (我正在使用Rails 4)

但我得到以下错误,我不明白如何解决。当用户尚未完成首选项表单(具有对首选项属性的验证)时,会发生这种情况 enter image description here

错误的终端显示

ActiveRecord::RecordNotSaved - Failed to save the new associated preference.:
  activerecord (4.2.0) lib/active_record/associations/has_one_association.rb:43:in `block in replace'
  activerecord (4.2.0) lib/active_record/associations/has_one_association.rb:98:in `block in transaction_if'
  activerecord (4.2.0) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'
  activerecord (4.2.0) lib/active_record/connection_adapters/abstract/transaction.rb:188:in `within_new_transaction'
  activerecord (4.2.0) lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'
  activerecord (4.2.0) lib/active_record/transactions.rb:220:in `transaction'
  activerecord (4.2.0) lib/active_record/associations/has_one_association.rb:98:in `transaction_if'
  activerecord (4.2.0) lib/active_record/associations/has_one_association.rb:33:in `replace'
  activerecord (4.2.0) lib/active_record/associations/singular_association.rb:17:in `writer'
  activerecord (4.2.0) lib/active_record/associations/builder/association.rb:123:in `preference='
  app/controllers/preferences_controller.rb:55:in `create'
  actionpack (4.2.0) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
  actionpack (4.2.0) lib/abstract_controller/base.rb:198:in `process_action'
  actionpack (4.2.0) lib/action_controller/metal/rendering.rb:10:in `process_action'
  actionpack (4.2.0) lib/abstract_controller/callbacks.rb:20:in `block in process_action'
  activesupport (4.2.0) lib/active_support/callbacks.rb:117:in `call'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional'
  activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:308:in `block (2 levels) in halting'
  public_activity (1.5.0) lib/public_activity/utility/store_controller.rb:25:in `store_controller_for_public_activity'
  activesupport (4.2.0) lib/active_support/callbacks.rb:427:in `block in make_lambda'
  activesupport (4.2.0) lib/active_support/callbacks.rb:307:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:234:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:169:in `block in halting'
  activesupport (4.2.0) lib/active_support/callbacks.rb:92:in `_run_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_process_action_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.0) lib/abstract_controller/callbacks.rb:19:in `process_action'
  actionpack (4.2.0) lib/action_controller/metal/rescue.rb:29:in `process_action'
  actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:31:in `block in process_action'
  activesupport (4.2.0) lib/active_support/notifications.rb:164:in `block in instrument'
  activesupport (4.2.0) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
  activesupport (4.2.0) lib/active_support/notifications.rb:164:in `instrument'
  actionpack (4.2.0) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
  actionpack (4.2.0) lib/action_controller/metal/params_wrapper.rb:250:in `process_action'
  activerecord (4.2.0) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
  actionpack (4.2.0) lib/abstract_controller/base.rb:137:in `process'
  actionview (4.2.0) lib/action_view/rendering.rb:30:in `process'
  actionpack (4.2.0) lib/action_controller/metal.rb:195:in `dispatch'
  actionpack (4.2.0) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch'
  actionpack (4.2.0) lib/action_controller/metal.rb:236:in `block in action'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:73:in `dispatch'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:42:in `serve'
  actionpack (4.2.0) lib/action_dispatch/journey/router.rb:43:in `block in serve'
  actionpack (4.2.0) lib/action_dispatch/journey/router.rb:30:in `serve'
  actionpack (4.2.0) lib/action_dispatch/routing/route_set.rb:802:in `call'
  warden (1.2.4) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.4) lib/warden/manager.rb:34:in `call'
  rack (1.6.4) lib/rack/etag.rb:24:in `call'
  rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
  rack (1.6.4) lib/rack/head.rb:13:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  activerecord (4.2.0) lib/active_record/query_cache.rb:36:in `call'
  activerecord (4.2.0) lib/active_record/connection_adapters/abstract/connection_pool.rb:647:in `call'
  activerecord (4.2.0) lib/active_record/migration.rb:378:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.0) lib/active_support/callbacks.rb:88:in `_run_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:734:in `_run_call_callbacks'
  activesupport (4.2.0) lib/active_support/callbacks.rb:81:in `run_callbacks'
  actionpack (4.2.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call'
  better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.3.0) lib/web_console/middleware.rb:28:in `block in call'
  web-console (2.3.0) lib/web_console/middleware.rb:18:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.0) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.0) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.0) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.0) lib/rails/rack/logger.rb:20:in `call'
  quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets'
  actionpack (4.2.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.4) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.0) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.0) lib/action_dispatch/middleware/static.rb:113:in `call'
  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.0) lib/rails/engine.rb:518:in `call'
  railties (4.2.0) lib/rails/application.rb:164:in `call'
  rack (1.6.4) lib/rack/content_length.rb:15:in `call'
  thin (1.5.1) lib/thin/connection.rb:81:in `block in pre_process'
  thin (1.5.1) lib/thin/connection.rb:79:in `pre_process'
  thin (1.5.1) lib/thin/connection.rb:54:in `process'
  thin (1.5.1) lib/thin/connection.rb:39:in `receive_data'
  eventmachine (1.0.9.1) lib/eventmachine.rb:193:in `run'
  thin (1.5.1) lib/thin/backends/base.rb:63:in `start'
  thin (1.5.1) lib/thin/server.rb:159:in `start'
  rack (1.6.4) lib/rack/handler/thin.rb:19:in `run'
  rack (1.6.4) lib/rack/server.rb:286:in `start'
  railties (4.2.0) lib/rails/commands/server.rb:80:in `start'
  railties (4.2.0) lib/rails/commands/commands_tasks.rb:80:in `block in server'
  railties (4.2.0) lib/rails/commands/commands_tasks.rb:75:in `server'
  railties (4.2.0) lib/rails/commands/commands_tasks.rb:39:in `run_command!'
  railties (4.2.0) lib/rails/commands.rb:17:in `<top (required)>'
  bin/rails:9:in `<top (required)>'
  spring (1.7.1) lib/spring/client/rails.rb:28:in `call'
  spring (1.7.1) lib/spring/client/command.rb:7:in `call'
  spring (1.7.1) lib/spring/client.rb:30:in `run'
  spring (1.7.1) bin/spring:49:in `<top (required)>'
  spring (1.7.1) lib/spring/binstub.rb:11:in `<top (required)>'
  /Users/ARTLoe/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
  bin/spring:13:in `<top (required)>'
  bin/rails:3:in `<main>'
  可以告诉我哪里出错了吗?

在我的用户和偏好模型中,我有以下内容:

class User < ActiveRecord::Base
  has_one :preference, dependent: :destroy
  accepts_nested_attributes_for :preference
end

class Preference < ActiveRecord::Base
  validates_presence_of :category_idealethnicity, presence: true, message: "can't be blank"
  validates_presence_of :category_idealreligion, presence: true, message: "can't be blank"

  belongs_to :user
  has_and_belongs_to_many :category_idealethnicity, dependent: :destroy
  has_and_belongs_to_many :category_idealreligion, dependent: :destroy
end

users_controller

class UsersController < ApplicationController
  respond_to :html, :xml, :json
  before_action :authenticate_user!, :set_user, only: [:show, :edit, :update, :destroy]

  def index
    ...
  end

  def show
    ....
  end

  def edit
    ...
  end

  def update
    ...
  end

  private
  def set_user
    @user = User.friendly.find(params[:id])
  end

  def user_params
    params.require(:user).permit(:email, :firstname, preference_attributes: [:town, category_idealreligion_ids: [], category_idealsmoke_ids: []])
  end
end

preferences_controller

class PreferencesController < ApplicationController
  before_action :authenticate_user!, :set_preference, only: [:show, :edit, :update, :destroy]

  def index
    @preferences = Preference.all
  end

  def show
    ...
  end

  def new
    @users = User.random
    @user = current_user
    @preference = @user.build_preference
  end

  def edit
    ...
  end

  def create
    @user = User.friendly.find(params[:user_id])
    @user.preference = Preference.new(preference_params)
    @preference = @user.preference

    respond_to do |format|
      if @preference.save
        format.html { redirect_to @preference, notice: 'Preference was successfully created.' }
        format.json { render :show, status: :created, location: @preference }
      else
        format.html { render :new }
        format.json { render json: @preference.errors, status: :unprocessable_entity }
      end
    end
  end

  def update
    ...
  end

  def destroy
    ...
  end

  private
  def set_preference
    @preference = Preference.find(params[:id])
  end

  def preference_params
    params.require(:preference).permit(:town, :user_id, category_idealethnicity_ids: [], category_idealreligion_ids: [])
  end
end

路由

Rails.application.routes.draw do
  devise_for :users
  resources :users do
    resources :preferences
  end
end

偏好表格

<div>
  <%= simple_form_for [@user, @preference] do |f| %>
    <%= f.error_notification %>
    <%= f.association :category_idealethnicity, collection: CategoryIdealethnicity.all, prompt: "select", label: false, as: :check_boxes %>
    <%= f.association :category_idealreligion, collection: CategoryIdealreligion.all, prompt: "select", label: false, as: :check_boxes %>
    <div class="form-actions">
      <%= f.button :submit %>
    </div>
  <% end %>
</div>

2 个答案:

答案 0 :(得分:1)

您的create方法对我来说很可疑。请尝试以下

def create
  @user = User.friendly.find(params[:user_id])
  @preference = @user.preference.new(preference_params)

  respond_to do |format|
    if @preference.save
      format.html { redirect_to @preference, notice: 'Preference was successfully created.' }
      format.json { render :show, status: :created, location: @preference }
    else
      format.html { render :new }
      format.json { render json: @preference.errors, status: :unprocessable_entity }
    end
  end
end

答案 1 :(得分:0)

  

问题的答案:显示我的创建方法是错误的。以下是正确的代码

def create
    @preference = Preference.new(preference_params)
    @preference.user = current_user

    respond_to do |format|
      if @preference.save
        format.html { redirect_to @preference, notice: 'Preference was successfully created.' }
        format.json { render :show, status: :created, location: @preference }
      else
        format.html { render :new }
        format.json { render json: @preference.errors, status: :unprocessable_entity }
      end
    end
  end