[英]user_id = nil on a non-nested active record association
从控制器进行构建时,我无法获取参考密钥进行更新。 我不确定控制器代码的rails约定适用于这种情况,并且无法在任何地方找到信息。
创建工具后,我不确定我的工具的user_id列始终为nil,并且不确定丢失了什么。
我想在不嵌套路线的情况下执行此操作,如何在不嵌套我的路线的情况下执行此操作?
这是我的模型(我正在为用户使用Devise):
class Tool < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :tools
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
这是我的控制器:
class ToolsController < ApplicationController
before_action :set_tool, only:[:show, :edit, :update, :destroy]
before_action :authenticate_user!, only:[:new, :destroy, :edit], notice: 'you must be logged in to proceed'
def index
@tools = Tool.all
end
def show
end
def new
@user = current_user
@tool = @user.tools.build
end
def create
@tool = Tool.new(tool_params)
@tool.save
redirect_to @tool
end
def edit
end
def update
@tool.update(tool_params)
redirect_to @tool
end
def destroy
@tool.destroy
redirect_to tools_path
end
private
def set_tool
@tool = Tool.find(params[:id])
end
def tool_params
params.require(:tool).permit(:name, :description)
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="actions">
<%= f.submit %>
</div>
<% end %>
这些是我的路线:
Rails.application.routes.draw do
devise_for :users
root 'tools#index'
resources :tools
end
这是我的架构:
ActiveRecord::Schema.define(version: 20150410082131) do
create_table "tools", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.string "name"
t.text "description"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
在create
方法中,您应该更改
@tool = Tool.new(tool_params)
new
到相似的一个
@tool = current_user.tools.build(tool_params)
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.