0

I have a rails app where I have has_many and belongs_to association. But I am having problems while trying to retrieve the elements. My Models are Events, Comments and Votes. Events has multiple Comments and Votes. Of Course Comments and Voted belong_to one event.

My schema is

    create_table "events",
        t.string   "etime"
        t.integer  "eid"
      end
    create_table "votes",
        t.integer  "eventid"
        t.string  "userid"
        t.integer  "event_id"
    end 

Associations:

    class Event < ActiveRecord::Base
    has_many :comments
    has_many :votes
    end
    class Votes < ActiveRecord::Base
        belongs_to :event
    end

I am trying to view all the votes for the events. The controller action is:

    @events = Event.all
@events.each do |event|
    event.votes.each do |vote|
        respond_to do |format|
            format.html
        end
    end 
end

View and error line:

    <%= @vote.userid %>

I get an error "Undefined Method "userid" for vote". In my controller, I render my eventid and it worked. So it seems to be a problem when I do it in the view.. Any idea What I could be doing wrong? I am completely lost on this one

  • It should be `event_id`, but are you really trying to show the id, or the vote? – Dave Newton Jun 19 '12 at 20:12
  • I am trying to show the vote. I had another field in my vote model by userid. I am trying to display both the event_id and userid. I deleted the userid as I was having problems earlier with another code. But I added it again. Same error for that(if I remove vote.eventid) – user1364813 Jun 19 '12 at 20:29

2 Answers2

0

Might be as simple as using event_id instead of eventid.

It's always worth it to run rails console and play around in there. You can usually autocomplete methods.

v = Vote.new
v.event<tab to get options>
Mark Bolusmjak
  • 23,606
  • 10
  • 74
  • 129
0

Somewhere you have got it all wrong, your table migrations, as in your foreign_key names are wrong, so are your primary keys.

In standard cases, all models have primary keys as id, just id.

For associating with other model, for example, a belongs_to :event association your vote model needs a , event_id column. These are rails standards

Lets assume, your associations /columns are correct, The error that you get is because your @vote object is nil , in your controller you need to assign/initialize the @vote variable to use it the view which you don't seem to be doing.

Rishav Rastogi
  • 15,484
  • 3
  • 42
  • 47
  • After the association was complete, the event_id was automatically created. But I added the field in my code. I added the @vote variable, but no help – user1364813 Jun 19 '12 at 20:40