【问题标题】:How to add another column that should be read-only in the view and can be changed explicitly via SQL query from the code only如何在视图中添加另一个应该是只读的列,并且只能通过代码中的 SQL 查询显式更改
【发布时间】:2014-09-24 13:34:02
【问题描述】:

我的 Ruby on Rails 4.1.4 应用程序中有一个表,我想添加另一个列,该列在视图中应该是只读的,并且只能通过代码中的 SQL 查询显式更改。

我怎样才能实现这样的行为?

提前致谢。

【问题讨论】:

    标签: sql ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    假设您使用的是强参数,您可以从控制器的强参数列表中删除该列。

    以下是来自strong_parameters github repo 的一些示例代码,用于了解您是否使用了强参数:

    class PeopleController < ActionController::Base
      # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
      # without an explicit permit step.
      def create
        Person.create(params[:person])
      end
    
      # This will pass with flying colors as long as there's a person key in the parameters, otherwise
      # it'll raise an ActionController::MissingParameter exception, which will get caught by
      # ActionController::Base and turned into that 400 Bad Request reply.
      def update
        person = current_account.people.find(params[:id])
        person.update_attributes!(person_params)
        redirect_to person
      end
    
      private
        # Using a private method to encapsulate the permissible parameters is just a good pattern
        # since you'll be able to reuse the same permit list between create and update. Also, you
        # can specialize this method with per-user checking of permissible attributes.
        def person_params
          params.require(:person).permit(:name, :age)
        end
    end
    

    person_params 中的内容就是 strong_parameters 的作用。

    【讨论】:

    • 如何知道我是否使用了强参数?
    • @FrozenHeart google "rails strong parameters" 看看你是否在你的控制器中使用它......更新答案以包括控制器中的强参数示例。您可能正在使用它,因为 IIRC 它带有 Rails 4
    • 很遗憾,我不明白在这种情况下我应该怎么做。我正在使用 Active Admin,但没有看到任何这样的代码
    • 您没有提到您正在使用活动管理员...看起来您应该能够在视图中将字段标记为禁用。这是你要找的吗? stackoverflow.com/questions/12703987/…
    • @FrozenHeart 嘿,如果这个答案对您有所帮助,如果您可以将其标记为“已接受”答案,那就太棒了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多