Rails - 使用text_field向数组添加元素

时间:2014-10-29 09:10:50

标签: ruby-on-rails arrays

我想做一些非常简单的事情:使用输入文本字段将元素添加到数组中。看起来很简单,我有点卡住了......

每个用户都有一个(单个)个人资料。每个配置文件都包含一个文本字段“entertainment”,它在ProfilesController中被序列化为一个数组。

我使用以下内容更新了具有固定文本的属性:

ProfilesController中的

方法

def update_entertainment
   @user = User.find_by(params[:id])
   @profile = @user.profile
   @user.profile.update(entertainment: ["the usual suspects"])
   redirect_to profile_path(current_user, tab:"entertainment")
end

profilesPatroller中的profile_params

def profile_params
   params.require(:profile).permit(:gender, :date_of_birth, :zip_code, :city, :state, :country, :marital_status, :entertainment )
end

表格

<div class="form-group">  
    <%= text_field :entertainment, :class => 'form-control' %>
    <%= button_to("+", :action => :update_entertainment, :method => :put, :remote => true) %>
</div>

但是,无论我尝试过什么(这都是很多),我无法将文本字段的输入推送到数组(而不仅仅是更新)。现在一次添加一个元素就行了。我真正想做的是让用户有机会将元素添加到数组中。

我正在使用Rails 4.0.x

2 个答案:

答案 0 :(得分:0)

原因是使用button_to而不是通常的形式。

Normal form而不是button_to解决了这个问题。

答案 1 :(得分:0)

<强>解决

在@ D.K的帮助下。和@anushka我能够解决这个问题。我更改了更改的行

@profile.entertainment << params[:entertainment] 

在ProfilesController中

@profile.entertainment << params[:entertainment]

并将表单更改为:

<div class="form-group">
  <%= form_tag(:action => :update_entertainment, :method=>'post', :multipart => true, :class => 'form-control') do %>
    <div class="input-group">
      <%= text_field_tag :entertainment, nil, :class => 'form-control form-group', :placeholder => 'add interests' %>
      <span class="input-group-btn">
      <%= submit_tag '+', class: 'btn btn-default' %>
      </span>
   </div>
  <% end %>
</div>