gpt4 book ai didi

ruby-on-rails - 访问其他模型

转载 作者:行者123 更新时间:2023-11-28 21:32:18 24 4
gpt4 key购买 nike

我正在努力让它发挥作用。我进行了适当的联想,但仍然失败。看看我的代码。

post.rb

class Post < ActiveRecord::Base
belongs_to :user
attr_accessible :content

before_create :format_content

validates :content, presence:true, length: {minimum:21}

def format_content
profil = self.user.profile
if profil.gender == "Mężczyzna"
"Wiadomość od spottera: #{self.content}"
elsif profil.gender == "Kobieta"
"Wiadomość od spotterki: #{self.content}"
end
end
end

post_spec.rb

describe "Properly formats content" do
let(:user) {FactoryGirl.create(:user)}
let!(:poscik) {FactoryGirl.create(:post) }
before(:each) {user.create_profile!(gender: "Kobieta", email: "donatella@dostojnie.pl")}

rspec_failures

Post creation valid should have content Failure/Error: poscik = user.posts.create(content: "Weird #{"a"*25}") NoMethodError: undefined method `gender' for nil:NilClass

如何正确访问模型中的其他类以及为什么找不到我的方法?我理解错误消息 - 它说我的配置文件类未定义


用户工厂

FactoryGirl.define do
factory :user do
sequence(:email) {|i|"maestro#{i}@dot.pl"}
password "kravmaga1290"
association :profile, factory: :profile, strategy: :build
end
end

最佳答案

看来您还没有创建类 Profile 的对象。我认为它是在提示您为获取 profile.gender 而调用的 nil 类。

尝试在工厂中添加这样的东西:

Factory.define :user do |f|
f.after_build do |user|
user.profile ||= Factory.build(:profile, :user => user)
end
end

当然,您还必须定义配置文件工厂。让我知道这是否有帮助

关于ruby-on-rails - 访问其他模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15187219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com