【问题标题】:NoMethodError: Undefined method `first_or_create' for "foo":StringNoMethodError:“foo”的未定义方法“first_or_create”:字符串
【发布时间】:2015-04-21 23:57:22
【问题描述】:

我以前在带有 Datamapper 的 Sinatra 应用程序中使用过这种方法,没有任何问题。 现在它似乎不起作用。任何想法表示赞赏。 我的测试:

scenario 'add hashtags to posts' do
visit '/'
add_post('Stacca', 
        'Hello! out there',
         %w(foo bar))
post = Post.first
 expect(post.hashtag.map(&:text)).to include('foo')
 expect(post.hashtag.map(&:text)).to include('bar')

结束

我的服务器

post '/posting' do
username = params['username']
message = params['message']
hashtag = params['hashtag'].split(' ').map do |hashtag|
hashtag.first_or_create(text: hashtag)
end
Post.create(username: username, message: message, hashtag: hashtag)
redirect to ('/')
end

我的模特:

class Post
include DataMapper::Resource
property :id, Serial
property :username, String
property :message, String

has n, :hashtag, through: Resource
end

和:

class Hashtag
include DataMapper::Resource
has n, :posts, through: Resource
property :id, Serial
property :text, String
end

谢谢

【问题讨论】:

    标签: ruby sinatra datamapper


    【解决方案1】:

    这一行:

    hashtag.first_or_create(text: hashtag)
    

    应该是:

    Hashtag.first_or_create(text: hashtag) # uppercase!
    

    否则,您只是尝试在从场景中获得的字符串(“foo”)上调用不存在的“first_or_create”方法。 'Hashtag' 是你的类,'hashtag' 是你的(字符串)变量。

    【讨论】:

      【解决方案2】:
      Hashtag.first_or_create(text: hashtag)
      

      Hashtag 应该是一个类 即你错过了首都

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-25
        相关资源
        最近更新 更多