Has_many and belongs_to relationship error

Hi i am getting following error

ActiveRecord::StatementInvalid in Blog#index

Showing app/views/blog/index.rhtml where line #10 raised:

Mysql::Error: #42S22Unknown column ‘posts.user_id’ in ‘where clause’:
SELECT * FROM posts WHERE (posts.user_id = 4)

Extracted source (around line #10):

7:

 

8: <% end %>
9:
10: <% for post in @posts %>
11:

12:

<%= h(post.posttitle) %>


13: <%= post.posttext %>

The code follows:

class Post < ActiveRecord::Base
belongs_to :user

end

class User < ActiveRecord::Base
has_many :posts
end

class BlogController < ApplicationController

def index
@user = User.find_by_login(‘bilal’)
@posts = @user.posts
@missions = Mission.find(:all)
end
end

index.rhtml is
<% for mission in @missions %>

<%= h(mission.missionname) %>

<%= mission.missiondescription %>
 
<% end %>

<% for post in @posts %>

<%= h(post.posttitle) %>

<%= post.posttext %>
 
<% end %>

Thanks marc. I have made the changes you suggested but the error remains
as is.

The blog controller and the index.rhtml looks as follows now

class BlogController < ApplicationController
def index
@user = User.find_by_login(‘bilal’)
@missions = Mission.find(:all)
end
end

<% for mission in @missions %>

<%= h(mission.missionname) %>

<%= mission.missiondescription %>
 
<% end %>

<% for post in @user.posts %>

<%= h(post.posttitle) %>

<%= post.posttext %>
 
<% end %>

I would get rid of @posts = @user.posts from your controller and change
the line 10 in your view to <% for post in @user.posts %>. There’s
really no need to set the @posts instance variable, and I don’t know why
but it seems its messing up your SQL statement.

bilal hameed wrote:

Hi i am getting following error

ActiveRecord::StatementInvalid in Blog#index

Showing app/views/blog/index.rhtml where line #10 raised:

Mysql::Error: #42S22Unknown column ‘posts.user_id’ in ‘where clause’:
SELECT * FROM posts WHERE (posts.user_id = 4)

Extracted source (around line #10):

7:

 

8: <% end %>
9:
10: <% for post in @posts %>
11:

12:

<%= h(post.posttitle) %>


13: <%= post.posttext %>

class BlogController < ApplicationController

def index
@user = User.find_by_login(‘bilal’)
@posts = @user.posts
@missions = Mission.find(:all)
end
end