使用Active Admin
时 - > Custom Page
- > page_action
,我在遵循代码中指向的代码块方面遇到了困难。我试图通过异常测试代码可达性。我不明白为什么如果我将异常放在代码中的第2位,我不会得到异常?
page_action :add_event, method: :post do
blogit_posts=params["featured_post"]["blog_posts_attributes"].values.map { |s|
{
:blogit_post_id=>s["blogit_post_id"],
:id=> s["id"] ? s["id"] : s["i/nd"],
:priority=>s["priority"],
:_destroy=>s["_destroy"]
}
}
blogit_posts.each do |blog_hash|
#raise "unknown" <-- 1. if i put here, I get exception for it
if blog_hash[:id]
b=BlogPost.find_by_id(blog_hash[:id].to_i)
else if blog_hash[:blogit_post_id]
b=BlogPost.find_by_blogit_post_id(blog_hash[:blogit_post_id].to_i)
end
#raise "unknown" <-- 2. if i put here, I **DO NOT** get exception for it
if blog_hash[:_destroy] && blog_hash[:_destroy]=="1"
b.is_featured=false # <--- trying to fix this code block
else
b.is_featured=true
end
b.priority =blog_hash[:priority].to_i
b.save
end
end
redirect_to admin_featuredpost_path, notice: "Featurd post updated "
end
答案 0 :(得分:1)
如果您尝试正确格式化代码,则会立即发现错误:
if blog_hash[:id]
b=BlogPost.find_by_id(blog_hash[:id].to_i)
else
if blog_hash[:blogit_post_id]
b=BlogPost.find_by_blogit_post_id(blog_hash[:blogit_post_id].to_i)
end
???
那就是说,你已经打开了if
,关闭了15行。应该使用elsif
用于意大利面if
或正确关闭嵌套if
。
答案 1 :(得分:1)
你可能遇到了这个障碍的问题:
if blog_hash[:id]
b=BlogPost.find_by_id(blog_hash[:id].to_i)
else if blog_hash[:blogit_post_id]
b=BlogPost.find_by_blogit_post_id(blog_hash[:blogit_post_id].to_i)
end
我相信你的意思是写下这个:
if blog_hash[:id]
b=BlogPost.find_by_id(blog_hash[:id].to_i)
elsif blog_hash[:blogit_post_id]
b=BlogPost.find_by_blogit_post_id(blog_hash[:blogit_post_id].to_i)
end
请注意elsif