Active Record Association不保存在数据库中

时间:2015-04-09 21:48:58

标签: ruby forms ruby-on-rails-4 activerecord associations

我有两种模式:

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变量吗?我试过这个,但它还没有解决问题...

这是如何运作的?

1 个答案:

答案 0 :(得分:0)

目前,您正在构建自己的工具。要将其与用户模型相关联,您需要按以下方式创建工具模型:

@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