So, I have this
def userposts
posts = Post.where(user_id: params[:id])
postnums = posts.map {|i| i.id }
postsWithInfo = posts.map{|i| {
post: i,
recipe: i.recipe,
recipepic: rails_blob_path(i.recipe.pic) if i.recipe?,
pics: i.pics.map{|p| rails_blob_path(p) }
}}
render json: {posts: postsWithInfo}, status: 200
end
recipe is null if there's no recipe, and that's what I want, but the problem is that recipepic is crashing the thing if i.recipe is null, and that if statement is doing nothing to stop it. Is there a way I can make it so that this works?
The error I get is
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:27: syntax error, unexpected `if' modifier, expecting '}'
...ails_blob_path(i.recipe.pic) if i.recipe?,
... ^~
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:27: syntax error, unexpected ',', expecting '}'
...ath(i.recipe.pic) if i.recipe?,
... ^
/home/dan/code/projects/project5/backend/app/controllers/posts_controller.rb:29: syntax error, unexpected '}', expecting `end'
}}
^
CodePudding user response:
try this way
postsWithInfo = posts.map do |i|
{
post: i,
recipe: i.recipe,
recipepic: i.recipe? ? rails_blob_path(i.recipe.pic) : nil,
pics: i.pics.map{|p| rails_blob_path(p) }
}
end