ciembor
ciembor

Reputation: 7337

Ruby DataMapper doesn't store has n / belongs_to

I have two DataMapper models:

class Address
  include DataMapper::Resource

  property :id, Serial
  property :url, String, :required => true

  has n, :logs
end

class Log
  include DataMapper::Resource

  property :id, Serial
  property :useragent, String

  belongs_to :address
end

I use Sinatra to create new addresses, and in another method logs which belongs to these addresses.

  # page after posting a form
  post '/' do
    @messages = []

    if (params[:url] =~ URI::regexp).nil?
      @messages.push('URL is not valid!')
    else
      address = Address.create(:url => params[:url])

      base36 = address.id.to_s(36)
      @messages.push(request.url + base36)
    end

    erb :index
  end

  # redirection from a short url
  get '/:base36' do |base36| 
    # probably not necessary...
    if base36 =~ /[[:alnum:]]+/
      begin
        id = base36.to_i(36)
        address = Address.get(id)

        log = Log.create(:useragent => request.user_agent)
        address.logs << log
        # log.save
        address.save
        # address.logs.save

        address.logs.length.to_s
        # redirect address.url
      rescue
        redirect '/'
      end
    else
      redirect '/'
    end
  end

The problem is, that new logs aren't stored in a database. address.logs.length.to_s Is 1 on every page reload (it should be incrementing). When I do this (in another method):

logs = Address.get(id).logs
@views = logs.length

views are always 0. What is wrong with this code?


OK, so I tried do push to the String field too long useragent. String is limited to 50 characters. People on #datamapper irc channel helped me, .save method returns false in this case and data isn't stored.

Upvotes: 0

Views: 294

Answers (2)

ciembor
ciembor

Reputation: 7337

OK, so I tried do push to the String field too long useragent. String is limited to 50 characters. People on #datamapper irc channel helped me, .save method returns false in this case and data isn't stored.

Upvotes: 1

phil pirozhkov
phil pirozhkov

Reputation: 4900

Comment says:

address.logs << log
# log.save

But the code doesn't say so. You should either create log with address passed

log = Log.create(:useragent => request.user_agent, :address => address)

either save the log after pushing it to log set:

log = Log.new(:useragent => request.user_agent)
address.logs << log
log.save # not a comment, just a self-explaining code

The relation in your case is stored in Log resource, so you should save it, not the Address.

Upvotes: 0

Related Questions