【问题标题】:Am I logically reiterating the same code block in Ruby?我是否在逻辑上重复了 Ruby 中的相同代码块?
【发布时间】:2020-12-31 01:30:44
【问题描述】:

这两行 Ruby 代码有什么区别?

if params.values.any? { |value| value == "" }

@post = current_user.posts.build(title: params[:post][:title], content: params[:post][:content])

它们使用的上下文分别如下:

post '/builds' do
  redirect_if_not_logged_in
  if params.values.any? {|value| value == ""}
    erb :'builds/new', #locals: {message: "Unable to Continue!"}
  else
    user = User.find(session[:user_id])
    @build = Build.create(title: params[:title], budget: params[:budget], user_id: params[:user.id])
    redirect to "/builds/#{@build.id}"
  end
end

post "/builds" do
  redirect_if_not_logged_in
  @build = current_user.builds.build(title: params[:post][:title], content: params[:build][:content])
  if @build.save
    redirect "/builds"
  else
    erb :"/builds/new.html"
  end
end

【问题讨论】:

  • 你的意思是除了这两条线之外基本上没有共同点?我不确定你在这里问什么。为什么同一路径有两个处理程序?
  • 我正在练习以不同的方式编写相同的代码,
  • 我不确定你在问什么。这两行完全不同,我什至无法找到它们相似的地方。
  • 好的,谢谢我错了。你回答成功了
  • 希望有帮助吗?这个 Ruby 代码看起来不错,但我不确定这些块之间的共性是什么,除了它们都声称要回答 /builds

标签: ruby activerecord sinatra


【解决方案1】:
  if params.values.any? {|value| value == ""}
     erb :'builds/new', #locals: {message: "Unable to Continue!"}

如果任何参数值为空,您在此处所做的是返回错误消息。如果用户没有填写页面上的某个表单域,就会发生这种情况。

 @post = current_user.posts.build(title: params[:post][:title], content: params[:post][:content])

这将使用给定的参数创建一个新的帖子对象。如果您没有第一个代码块,则可能会将其中一个值设置为空字符串 ("")。

还有其他方法可以做到这一点(特别是模型级验证),但希望这可以帮助您弄清楚这里发生了什么。

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多