ARTLoe
ARTLoe

Reputation: 1799

Can't link user_id to new created object - rails 4

i am new to rails so any help would be much appreciated. I have the models userrs (recruiters) and adverts. Userr has_many adverts and Advert belongs to a user.

Question: when a userr creates an advert i want the created advert to be automatically linked to the userr that created the advert. I am unsure how to go about this in the controller

i know how to assign an advert to a user in the console. but unsure how to do this in the controller

console

advert = Advert.first
advert.userr_id = 3
advert.save

route

Rails.application.routes.draw do
  resources :adverts

  resources :feedbacks

  devise_for :userrs
  devise_for :userjs
  root 'static_pages#homepg'
  get     'affiliate',    to: 'static_pages#affiliatepg'
  get     'terms',        to: 'static_pages#termpg'
  get     'privacy',      to: 'static_pages#privacypg'
  get     'contact',      to: 'static_pages#contactpg'
  get     'about',        to: 'static_pages#aboutpg'
  get     'recruiters',   to: 'static_pages#recruiterpg'
  get     'jobseekers',   to: 'static_pages#jobseekerpg'
  get     'approach',     to: 'static_pages#approachpg'
  get     'sector',       to: 'static_pages#sectorpg'
  get     'news',         to: 'static_pages#newspg'
  get     'offer',        to: 'static_pages#offerpg'
  get     'refferal',     to: 'static_pages#refferalpg'
end

i placed the below code: in my advert controller under the create function:

def create
    @userr = Userr.find(params[:userr_id])
    @advert = @userr.adverts.build(params[:advert])
    if @advert.save
      flash[:notice] = 'Successfully created advert'
      redirect_to recruiters_path
    else
      render action: 'new'
    end
  end

but i got the error:

Couldn't find Userr without an ID

log - error message

Started GET "/adverts/new" for 127.0.0.1 at 2015-04-02 14:59:38 +0100
Processing by AdvertsController#new as HTML
Completed 404 Not Found in 1ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Userr without an ID):
  app/controllers/adverts_controller.rb:20:in `new'


  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_source.erb (8.2ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_trace.html.erb (3.4ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (0.8ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_web_console.html.erb (0.8ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/diagnostics.html.erb within rescues/layout (27.3ms)


Started GET "/adverts/new" for 127.0.0.1 at 2015-04-02 14:59:38 +0100
Processing by AdvertsController#new as HTML
Completed 404 Not Found in 1ms (ActiveRecord: 0.0ms)

ActiveRecord::RecordNotFound (Couldn't find Userr without an ID):
  app/controllers/adverts_controller.rb:20:in `new'


  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_source.erb (8.1ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_trace.html.erb (3.0ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_request_and_response.html.erb (0.9ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_web_console.html.erb (0.8ms)
  Rendered /Users/ARTLoe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/diagnostics.html.erb within rescues/layout (26.2ms)

Schema

ActiveRecord::Schema.define(version: 20150330233948) do

  create_table "adverts", force: true do |t|
    t.string   "title"
    t.text     "content"
    t.integer  "category_jobtype_id"
    t.integer  "category_positiontype_id"
    t.integer  "salarystart"
    t.integer  "salaryend"
    t.integer  "category_country_id"
    t.string   "city"
    t.string   "town"
    t.string   "postcode"
    t.integer  "category_editorialapproval_id"
    t.integer  "category_applicationrequest_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "userr_id"
  end

  create_table "userrs", 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   "firstname"
    t.string   "lastname"
    t.string   "companyname"
    t.integer  "category_businesstype_id"
  end

  add_index "userrs", ["email"], name: "index_userrs_on_email", unique: true
  add_index "userrs", ["reset_password_token"], name: "index_userrs_on_reset_password_token", unique: true

model

class Advert < ActiveRecord::Base
  belongs_to :user
end

class Userr < ActiveRecord::Base
  has_many :adverts
end

controller: Advert

class AdvertsController < ApplicationController
  respond_to :html, :xml, :json
  before_action :set_advert, only: [:show, :edit, :update, :destroy]

  def index
    @adverts = Advert.all
    respond_with(@adverts)
  end

  def show
    respond_with(@advert)
  end

  # def new
  #   @advert = Advert.new
  #   respond_with(@advert)
  # end

  def new
    @userr = Userr.find(params[:userr_id])
    @advert = @userr.adverts.build
    respond_with(@advert)
  end

  def edit
  end

  # def create
  #   @advert = Advert.new(advert_params)
  #   @advert.save
  #   respond_with(@advert)
  # end

  def create
    @userr = Userr.find(params[:userr_id])
    @advert = @userr.adverts.build(params[:advert])
    if @advert.save
      flash[:notice] = 'Successfully created advert'
      redirect_to recruiters_path
    else
      render action: 'new'
    end
  end

  def update
    @advert.update(advert_params)
    respond_with(@advert)
  end

  def destroy
    @advert.destroy
    respond_with(@advert)
  end

  private
    def set_advert
      @advert = Advert.find(params[:id])
    end

    def advert_params
      params.require(:advert).permit(:title, :content, :category_jobtype_id, :category_positiontype_id, :salarystart, :salaryend, :category_country_id, :city, :town, :postcode, :category_editorialapproval_id, :category_applicationrequest_id)
    end
end

form for advert

<%= simple_form_for(@advert) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= f.input :title %>
    <%= f.input :content %>
    <%= f.association :category_jobtype, collection: CategoryJobtype.all, prompt: "select a category" %>
    <%= f.association :category_positiontype, collection: CategoryPositiontype.all, prompt: "select a category" %>
    <%= f.input :salarystart %>
    <%= f.input :salaryend %>
    <%= f.association :category_country, collection: CategoryCountry.all, prompt: "select a category" %>
    <%= f.input :city %>
    <%= f.input :town %>
    <%= f.input :postcode %>
    <%= f.association :category_editorialapproval, as: :radio_buttons %>
    <%= f.association :category_applicationrequest, as: :radio_buttons %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

any help will be appreciated

Upvotes: 0

Views: 64

Answers (1)

Oleg K.
Oleg K.

Reputation: 1549

First, you need to add userr_id to params:

 def advert_params
    params.require(:advert).permit(:userr_id, :title, :content, :category_jobtype_id, :category_positiontype_id, :salarystart, :salaryend, :category_country_id, :city, :town, :postcode, :category_editorialapproval_id, :category_applicationrequest_id)
 end

Second, add userr_id to the form:

 <%= simple_form_for(@advert) do |f| %>
   <%= f.hidden_field(:userr_id) %>

Third, change the param name in create:

 def create
     @userr = Userr.find(params[:advert][:userr_id])

You can do the same via routes, without altering the form. It's much cleaner but needs more source changes. I can't give you the full syntax here, but it will look like the following:

#routes.rb
resources :userrs do
    resources :addverts
end

And the advert's form will become /userrs/[user-id]/adverts, so you'll be able to get the user id from the url instead of the form field. But you'll need to change all the path shortcuts.

Upvotes: 1

Related Questions