【问题标题】:Rails 5 unable to complete "belongs_to"Rails 5 无法完成“belongs_to”
【发布时间】:2020-04-02 20:40:22
【问题描述】:

多年后我正在使用 Rails 5。我使用的最后一个版本是 Rails 3。不知何故,我无法让“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", 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

【问题讨论】:

    标签: link-to belongs-to ruby-on-rails-5.2


    【解决方案1】:

    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(符号)一样使用它。

    【讨论】:

    • 这是第二个。它实际上是模型中的 has_many :campaigns .. 我只是在上面打错了。任何其他原因导致它无法正常工作? (我将其设置为“可选”,因为我遇到了同样的错误。)
    • 可能与迁移有关。但在此之前,请尝试在 rails 控制台中创建一个用户并将其设置为该活动。让我们看看它会产生什么错误。
    • 啊...即使在我使用 Rails 还不错的时候,我的控制台也很糟糕。您能否通过命令运行我来执行此操作(设置用户在控制台中进行活动。)
    • 我不完全了解您的模型属性,但您可以尝试类似的方法:user = User.create(name: 'mystic cola') | user.campaigns.create(name: 'something') 我使用 '|'分隔行。
    • NameError: undefined local variable or method user' for main:Object from (irb):2 and if I do: user = User.create(UName: 'mystical', email: 'mystical@gmail.com', password: 'xxx') | user.campaigns.create(name: 'something') I get: NoMethodError: undefined method campaigns' for nil:NilClass
    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 2017-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多