簡體   English   中英

活動記錄關聯未保存在數據庫中

[英]Active Record Association not saving in database

我有兩個模型:

class Tool < ActiveRecord::Base
    belongs_to :user
end

class User < ActiveRecord::Base
  has_many :tools, dependent: :destroy
end

我創建了一個遷移以提供模型的外鍵:

class AddUserIdToTool < ActiveRecord::Migration
  def change
    add_column :tools, :user_id, :integer
  end
end

我有以下表格:

<%= form_for @tool, :html => { :multipart => true } do |f| %>
  <% if @tool.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@tool.errors.count, "error") %> prohibited this tool from being saved:</h2>

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

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.file_field :tool_image %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

每當我提交表單時,外鍵都不會更新(user_id)。 我在控制台中看到以下內容:

irb(main):002:0> Tool.last
  Tool Load (0.0ms)  SELECT  "tools".* FROM "tools"  ORDER BY "tools"."id" DESC LIMIT 1
=> #<Tool id: 6, name: "wrench2", description: "another wrench", created_at: "2015-04-09 21:38:47", updated_at: "2015-04
-09 21:38:47", tool_image_file_name: "wrench.jpg", tool_image_content_type: "image/jpeg", tool_image_file_size: 3424, to
ol_image_updated_at: "2015-04-09 21:38:43", user_id: nil>
irb(main):003:0>

如您所見, user_idnil

這是我的控制器:

class ToolsController < ApplicationController
  before_action :authenticate_user!, only: [:new, :destroy, :edit, :update], notice: 'you must sign in first!'
  before_action :set_tool, only: [:show, :edit, :update, :destroy]

  # GET /tools
  # GET /tools.json
  def index
    @tools = Tool.all
  end

  # GET /tools/1
  # GET /tools/1.json
  def show
  end

  # GET /tools/new
  def new
    @tool = Tool.new
  end

  # GET /tools/1/edit
  def edit
  end

  # POST /tools
  # POST /tools.json
  def create
    @tool = Tool.new(tool_params)

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

  # PATCH/PUT /tools/1
  # PATCH/PUT /tools/1.json
  def update
    respond_to do |format|
      if @tool.update(tool_params)
        format.html { redirect_to @tool, notice: 'Tool was successfully updated.' }
        format.json { render :show, status: :ok, location: @tool }
      else
        format.html { render :edit }
        format.json { render json: @tool.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tools/1
  # DELETE /tools/1.json
  def destroy
    @tool.destroy
    respond_to do |format|
      format.html { redirect_to tools_url, notice: 'Tool was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_tool
      @tool = Tool.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def tool_params
      params.require(:tool).permit(:name, :description, :tool_image, :user_id)
    end

end

我如何用已登錄用戶的ID更新user_id? 我是否必須在表單中包含一個隱藏字段或類似的內容?

我還必須在我的控制器的強參數中允許user_id變量嗎? 我已經嘗試過了,但是還沒有解決問題...

這是如何運作的?

當前,您正在自行構建工具。 要將其與用戶模型相關聯,您需要通過以下方式創建工具模型:

@user.tools.build

它將使用所屬模型的正確user_id創建一個新的ActiveRecord工具模型。 但是要成為父母,您需要從參數中獲取其ID。 可以通過以下方式完成:

@user = User.find(params[:user_id])

注意:為使您的路線有可能被相應地嵌套(請在此處閱讀更多信息: http : //guides.rubyonrails.org/routing.html

因此,總的來說,您的新操作應如下所示:

def new
  @user = User.find(params[:user_id])
  @tool = @user.tools.build
end

在你的routes.rb中

resources :users do
  resources :tools
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM