views:

130

answers:

1

I have created a blog, it will have posts, and the posts are created by the users. I already have a login system in my blog. And I have made the relation between a user and his posts. Now when I want to add a new post I want Rails to autofill the user_id field.

Should I add a hidden field and add the user_id from the session where I saved it in?

Or does Ruby on Rails have its own way to deal with relations and using IDs?

@edit:

the model:

class Post < ActiveRecord::Base
  validates_presence_of :subject, :body
  has_many :comments
  belongs_to :user 
end

the controller:

....
  def new
    @post = Post.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end
...
A: 

If you want to ensure that a blogger's posts are associated with the correct user, then don't use a form field for this at all, since their values can be changed by the end user. Better to rely on the login system that you have and do something like this when the blog-post form is submitted:

def create
  @post = current_user.posts.build(params[:post])
  if @post.save
    ...
  else
    ...
  end
end

This is assuming that you have a current_user method, perhaps in application.rb, that fetches the current user via your login system. Perhaps something like:

def current_user
  @current_user ||= User.find(session[:user_id])
end

and also assuming that you have put has_many :posts in User.rb.

Jordan Brough
Thank you for your help. I already registerd the user. so i ended up in the controller where i made the post added the line @post.user_id = User.currentWorks like a charm thanks for your input
arcooverbeek