【发布时间】:2014-09-24 13:34:02
【问题描述】:
我的 Ruby on Rails 4.1.4 应用程序中有一个表,我想添加另一个列,该列在视图中应该是只读的,并且只能通过代码中的 SQL 查询显式更改。
我怎样才能实现这样的行为?
提前致谢。
【问题讨论】:
标签: sql ruby-on-rails ruby ruby-on-rails-4
我的 Ruby on Rails 4.1.4 应用程序中有一个表,我想添加另一个列,该列在视图中应该是只读的,并且只能通过代码中的 SQL 查询显式更改。
我怎样才能实现这样的行为?
提前致谢。
【问题讨论】:
标签: sql ruby-on-rails ruby ruby-on-rails-4
假设您使用的是强参数,您可以从控制器的强参数列表中删除该列。
以下是来自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 的作用。
【讨论】: