我正在尝试使用来自form_for文本字段的用户输入的强参数将字符串值附加到Postgresql模型(“product.rb”)的两个数组列(“good_product”&“bad_product”)。我找到了两种方法(<<& find_by_sql)来实现这个目标,但无法工作。
例如,通过form_for输入提交的“产品3”应添加到{“产品1”,“产品2”,_______}(如果阵列中存在其他产品)或空数组(如果尚未添加产品) )。
型号:product.rb
class Product < ActiveRecord::Base
serialize :good_product, Array
serialize :bad_product, Array
end
Controller:products.controller.rb
def new
@product = Product.new
end
def create
@product = Product.new(product_params)
@product.good_product ||= []
@product.bad_product ||= []
@product.good_product << :good_product
@product.bad_product << :bad_product
redirect_to '/products'
end
private
def product_params
params.require(:product).permit(:good_product => [], :bad_product => [])
end
end
查看:new.html.erb
<%= form_for @product, url: products_path do |f| %>
<%= f.label :good_product, "Good Product" %>
<%= f.text_field :good_product %>
<%= f.label :bad_product, "Bad Product" %>
<%= f.text_field :bad_product %>
<%= f.submit 'Submit' %>
<% end %>
架构:schema.rb
create_table "products", force: :cascade do |t|
t.string "good_product", default: [], array: true
t.string "bad_product", default: [], array: true
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "products", ["user_id"], name: "index_products_on_user_id", using: :btree
或者,代替“&lt;&lt;”,我在Controller中尝试了这个:
def create
@product = Product.new(product_params)
Product.find_by_sql(["UPDATE products SET good_product = array_append(good_product, '?') WHERE user_id = ?", @product.good_product, current_user]);
Product.find_by_sql(["UPDATE products SET bad_product = array_append(bad_product, '?') WHERE user_id = ?", @product.bad_product, current_user]);
redirect_to '/products'
end
谢谢大家的帮助!