2015-11-14 2 views
0

По какой-то причине мои пользователи не ассоциируются с объектом при создании объекта. Каждый раз, когда я добавляю новую «индустрию», 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 
+1

Мне любопытно; где в вашем коде вы присваиваете 'user' объекту' @ industry'? Кажется, я ничего не могу найти, что вполне может быть причиной того, что 'user_id' является' nil'. –

+0

Является ли индустрия принадлежностью к какому пользователю? вы отправляете его из формы? или как вы ожидаете, что он будет заселен? Просто напишите его так же, как вы сказали, что назначаете его с консоли ... –

ответ

1
def create 
    @industry = Industry.new(industry_params) 
    authorize @industry 
    @industry.user = current_user 
    # blah-blah 
end 
+0

Спасибо! Все еще изучая тонкости RoR. Теперь я понимаю. оцените помощь. – user3787971

+0

Если вы хотите, чтобы на одной строке: '@industry = Industry.new (industry_params.merge (user: current_user)' – Statyx

Смежные вопросы