0

In rails console doing User.first and Post.first works fine. Post.first.user works fine but User.first.posts gives me an Undefined method error

The models:

class User < ActiveRecord::Base
    attr_accessible :role :user_email, :user_name

    has_many :posts
end

and

class Post < ActiveRecord::Base
    attr_accessible :content, :status, :title, :user_id

    belongs_to :user
    has_many :comments
end

When I create a new project everything works fine but in this case I did something different. I adapted an existing database (sqlite) from another web application (non-rails) to the rails. What I did was rename columns to fit rails conventions and where previously I was using user name as unique key and used that to link to post owners I changed the column name to user_id and updated all the values to the relevant user id. I changed the column type and values to int values too.

Same goes for Comment: Comment.first.post works but Post.commments gives the undefined method error.

When doing User.joins(:post(s)) I get the error "Association named 'posts' was not found" but Post.joins(:user) works fine.

Edit: Shame on me - I left out relevant information I didn't think was relevant.

Anyway - I had a column called role so the User model had attr_accessible :role --- once > I removed that everything worked like intended.

I however don't understand why this should make a difference. This: > https://github.com/ryanb/cancan/wiki/Role-Based-Authorization user model has :role and I > would assume any user based app would have has_many dependency and thus fail like mine did.

... or is there something else I'm missing?

Bjorn
  • 455
  • 4
  • 13
  • 1
    Have you changed the table name too? – MurifoX Jun 14 '12 at 14:55
  • adding on what @MurifoX, Specifically Post -> Posts – Bedasso Jun 14 '12 at 15:00
  • Yes, table name is posts. I basically ran generate for all the models in a vanilla app, then renamed the tables and columns in the old db to match everything in the generated one and then renamed the db file. – Bjorn Jun 14 '12 at 18:49
  • Shame on me - I left out relevant information I didn't think was relevant. Anyway - I had a column called role so the User model had attr_accessible :role --- once I removed that everything worked like intended. I however don't understand why this should make a difference. This: https://github.com/ryanb/cancan/wiki/Role-Based-Authorization user model has :role and I would assume any user based app would have has_many dependency and thus fail like mine did. ... or is there something else I'm missing? – Bjorn Jun 14 '12 at 23:38

0 Answers0