Search code examples
link-tobelongs-toruby-on-rails-5.2

Rails 5 unable to complete "belongs_to"


I'm using Rails 5 after many years. The last version I used was Rails 3. Somehow I can't get "belongs_to" working anymore. I've read all the suggested threads... but I'm just not getting it.

class User < ApplicationRecord
  has_many :campaigns

class Campaign < ApplicationRecord
  belongs_to :user, optional: true

But if I try to link a campaign to its User...

<%= link_to @campaign.user.UName, user_path %> </a></div>

I need a way to link a campaign to its user... Maybe I'm just a little rusty... I don't remember having ANY trouble linking, for example, a post's author before.

undefined method `UName' for nil:NilClass

schema.rb

 create_table "campaigns", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.string "category"
    t.string "artist"
    t.string "backer"
    t.string "update_title"
    t.text "update_desc"
    t.timestamp "update_time"
    t.text "faq"
    t.string "comments"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.float "goal", limit: 53
    t.string "type"
    t.timestamp "start_date"
    t.timestamp "end_date"
    t.string "video"
    t.integer "user_id"
  end

create_table "users", options: "ENGINE=InnoDB DEFAULT CHARSET=latin1", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.boolean "superadmin", default: false, null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.string "UName"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

Solution

  • link_to actually generates an 'a' tag, wrapping it with an 'a' tag is unnecessary. You can use link_to like bellow:

    <%= link_to @campaign.user.name, @campaign.user %>
    

    When you call @campaign.user, the user is returning nil. This could happen for two reasons:

    1. There is no relationship between that user and campaign. (Because you set it optional optional: true)
    2. You couldn't set the relationship between models properly.

    If the reason is the second one, I bet it's because of has_many campaigns line. As I know, you should use it like has_many :campaigns (symbol).