just a guess but it seems that your session[:user] is just storing the id, you need to do:
@user = User.find(session[:user])
or something along those lines to fetch the user from the database (along with its associations).
It's good to do the above in a before filter too.
As a comment can belong to a single post only, you do not need an association table (post_comments). You just need a simple one-to-many relationship.
Your post comment would be:
class Post < ActiveRecord::Base
has_many :comments
...
end
And comment would be like this:
class Comment < ActiveRecord::Base
belongs_to :post
...
end
Just make sure that you have the necessary post_id
column in the comments
table (you can check the db/schema.rb
file). If that is missing, you can use the following migration to add it:
class AddPostIdToComments < ActiveRecord::Migration
def change
add_column :comments, :post_id, :integer
add_index :comments, :post_id
end
end
You also need to make sure you keep somewhere the reference to the post, whenever a user tries to create a comment to a post. You can add this in a hidden field to your comments/new.html.erb
template. You could set the hidden field in the new
action, in PostsController, after passing it through the URL.
So, in your posts/show.html.erb
template you would have:
<%= link_to "Add Comment", new_comment_path(post_id: @post.id) %>
In your new
action, in PostsController
:
def new
@comment = Comment.new(post_id: params[:post_id])
end
And finally the hidden field in your form would be:
<%= f.hidden_field :post_id %>
Finally, add the post_id parameter to the list of permitted parameters in CommentsController
.
Best Solution
I'm guessing you are not logged in when the error is thrown. The NoMethod is not referring to #authorized?. It is actually referring to the #login method of current_user. If you aren't logged in, then current_user is nil, resulting in NoMethod when current_user.login is called within #authorized?.
Any helper like authorized? that checks user status should include checking logged_in? first to bypass this problem. Try this...
That way you bounce out of the conditional if not logged in, and you don't try to access #login method unless you actually have an object available.
You might also look into some of the available role-based authentication schemes that work with Restful_Authentication. If your access patterns are going to be any more complex than just checking for an admin, then it will be easier to use one of those plugins.
Incidentally, farther down in authenticated_system.rb you will find this code:
This is what makes methods in this module available as helper methods in the views. If you add a method to authenticated_system.rb that returns user status (for instance, something like #superuser?), you will need to add that method symbol to the base.send call in this code. Again, if you find yourself writing a lot of code for access control, learning one of the plugins would be in order.