10

I have a model, view and controller for a view (Feed) that doesn't have any "local" data. That is, the data is grabbed via a web service call to a client site and rendered in a local view.

The local site needs to verify that the object to grab from the remote site is valid (by verifying that the User that owns the Feed has a valid account) and then it displays it.

I had the logic to grab the data from the remote feed in a Feed model. Then the Feed controller takes the URL param for the feed id, passes it to the model getFeed function, and displays it.

However, since there's no table, the Feed.getFeed(params[:feed_id]) call in the controller was returning an error saying there is no table Feed.

Should I delete the Feed model and just make the getFeed function a helper function? What's the proper Rails way to deal with models with no table?

user101289
  • 9,888
  • 15
  • 81
  • 148
  • I believe the solution in [this answer](http://stackoverflow.com/a/14389234/877472) is what you're looking for. Essentially a plain 'ol class is all you need. You can then add Rails and active-whatever modules as needed. – Paul Richter Apr 11 '14 at 23:49

2 Answers2

6

Just because you're using Rails, it doesn't mean every model has to inherit from ActiveRecord::Base

In your situation, I'd simply do something along these lines:

# app/models/feed.rb
class Feed
  def initialize(feed_id)
    @feed_id = feed_id
  end

  def fetch
    # ... put the web-service handling here
  end

  # encapsulate the rest of your feed processing / handling logic here
end

# app/controllers/feeds_controller.rb
class FeedsController < ActionController::Base
  def show
    @feed = Feed.new(params[:feed_id])
    @feed.fetch

    # render
  end
end

Remember: it's Ruby on Rails, not just Rails. You can do a lot more than just ActiveRecord models.

dnch
  • 9,565
  • 2
  • 38
  • 41
  • I tried removing the inheritance and now am getting an error complaining that the function does not exist-- is this the purpose of you `initialize` method? – user101289 Apr 11 '14 at 23:58
  • while his description is different than his title, this is not a good answer for the title question, as there are valid reasons to want an AR model without a backing database table. – toobulkeh Nov 03 '15 at 16:17
  • The answer is fine - the solution in these cases is to simply not inherit from `ActiveRecord::Base`, but take what is required, like validations. See [rails-model-without-a-table](http://stackoverflow.com/questions/14389105/rails-model-without-a-table) – Epigene Nov 06 '15 at 13:38
-4

You can make an attr_accessor in your model

class Feed < ActiveRecord::Base
  attr_accessor :feed

It will represent feed as a temporary variable for your controller to pass the data.

Trip
  • 26,756
  • 46
  • 158
  • 277