由于某些原因,我的用户在创建对象时没有与对象关联。每次我添加一个新的“行业”时,user_id就会变为零。我可以在控制台中更新它,但是当我创建这个行业时它无法正常工作。
user.rb
class User < ActiveRecord::Base
has_many :industries
has_many :categories
has_many :startups
end
Industry.rb
class Industry < ActiveRecord::Base
belongs_to :user
has_many :categories
end
industries_controller.rb
class IndustriesController < ApplicationController
before_action :set_industry, only: [:show, :edit, :update, :destroy]
def index
@industries = Industry.all.order("created_at DESC").paginate(:page => params[:page], :per_page => 20)
authorize @industries
end
def show
@categories = @industry.categories
end
def new
@industry = Industry.new
authorize @industry
end
def edit
end
def create
@industry = Industry.new(industry_params)
authorize @industry
respond_to do |format|
if @industry.save
format.html { redirect_to @industry, notice: 'industry was successfully created.' }
format.json { render :show, status: :created, location: @industry }
else
format.html { render :new }
format.json { render json: @industry.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @industry.update(industry_params)
format.html { redirect_to @industry, notice: 'Industry was successfully updated.' }
format.json { render :show, status: :ok, location: @indsutry }
else
format.html { render :edit }
format.json { render json: @industry.errors, status: :unprocessable_entity }
end
end
end
def destroy
@industry.destroy
respond_to do |format|
format.html { redirect_to industries_url, notice: 'Inustry was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_industry
@industry = Industry.find(params[:id])
authorize @industry
end
# def correct_user
# @industry = current_user.industries.find_by(id: params[:id])
#redirect_to industries_path, notice: "Not authorized to edit this Industry" if @industry.nil?
# end
def industry_params
params.require(:industry).permit(:name)
end
end
模式
create_table "industries", force: true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
create_table "users", force: true 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"
t.string "role"
t.string "name"
end
答案 0 :(得分:1)
def create
@industry = Industry.new(industry_params)
authorize @industry
@industry.user = current_user
# blah-blah
end