Rails 5无法完成“ belongs_to”

多年以后,我一直在使用Rails 5。我使用的最后一个版本是Rails3。以某种方式,我无法继续使用“ belongs_to”。我已经阅读了所有建议的线程...但是我没有理解。

class User < ApplicationRecord
  has_many :campaigns

class Campaign < ApplicationRecord
  belongs_to :user,optional: true

但是,如果我尝试将广告系列链接到其用户...

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

我需要一种将广告系列与其用户链接的方法...也许我只是有点生疏...我不记得链接时遇到任何麻烦,例如以前的帖子作者。

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",force: :cascade do |t|
    t.string "email",default: "",null: false
    t.string "encrypted_password",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
achievekey 回答:Rails 5无法完成“ belongs_to”

link_to实际上会生成一个“ a”标签,而不必用“ a”标签包装它。您可以像下面这样使用link_to:

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

调用@campaign.user时,用户返回nil。 发生这种情况可能有两个原因:

  1. 该用户与广告系列之间没有任何关系。 (因为您将其设置为可选的optional: true
  2. 您无法正确设置模型之间的关系。

如果原因是第二个原因,我敢打赌,这是因为has_many campaigns行。据我所知,您应该像has_many :campaigns(符号)那样使用它。

本文链接:https://www.f2er.com/2524444.html

大家都在问