我从控制器构建时无法更新引用密钥。我不确定控制器代码的rails约定对于这种事情是什么,并且无法在任何地方找到信息。
我创建工具后,我的工具的user_id列始终为零,但不确定缺少什么。
我想在没有嵌套路线的情况下这样做,如何在不嵌套路线的情况下做到这一点?
这是我的模型(我正在为用户使用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
答案 0 :(得分:1)
在create
方法中,您应该更改
@tool = Tool.new(tool_params)
来自new
@tool = current_user.tools.build(tool_params)
祝你好运!