Ruby中的Map不关心我的if语句

nc1teljy  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(145)

所以我有这个

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的话recipe就是null,这也是我想要的,但问题是recipepic在i.recipe是null的情况下崩溃了,而且if语句没有做任何事情来阻止它,有没有办法让它正常工作呢?
我得到的错误是

/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'
}}
^
1tuwyuhd

1tuwyuhd1#

试试这条路

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

相关问题