开发者

finding a User object in ruby on rails

开发者 https://www.devze.com 2023-03-25 13:29 出处:网络
Ruby on rails noob here. User fields relevant to this question: id (prim. key). Post fields relevant to this question: id, user_id (fk). The foreign key is user_id of Posts which is connected to id o

Ruby on rails noob here.

User fields relevant to this question: id (prim. key). Post fields relevant to this question: id, user_id (fk). The foreign key is user_id of Posts which is connected to id of Users. Is the following the right syntax? I want to grab the User object who posted the current post: (this is in controllers/posts_controller.rb)

@id = Post.find(params[:id]).user_i开发者_开发技巧d 
@user = User.find(@id)

You can see the context of the code below:

def sendMessage
  #@user = current_user
  @id = Post.find(params[:id]).user_id 
  @user = User.find(@id)
  UserMailer.welcome_email(@user).deliver
  respond_to do |format|
      format.html { render :nothing => true, :status => :ok }
  end
end

The reason I'm asking is because an email is not getting sent to the user who created the post. Now, I know that this isn't an email issue because, as a test, I tried commenting out the two lines in question and simply using:

@user = current_user

...and this sends an email to the user who's logged in (but this isn't what I want).

Thanks in advance,

Matt


You should have your models set up as follows:

class Post < ActiveRecord::Base

  belongs_to :user

end

class User < ActiveRecord::Base

  has_many :posts

end

Then in your controller you can do:

@post = Post.find(params[:id])
@user = @post.user


You should set the proper relations in the model.

I guess 'has_many :posts' in User and 'belongs_to :user' in Post.

Then you'll be able to do:

@user = Post.find(params[:id]).user
0

精彩评论

暂无评论...
验证码 换一张
取 消