Rails2か月目の初心者です。基本的な部分が分かっていなかったらすみません。
###前提・実現したいこと
1.Railsでform_for を利用して、配列に情報をいれたい。
2.その情報を正しく編集したい。
###発生している問題・エラーメッセージ
■View
rails
1**Show** 2<p> 3 <strong>Content2:</strong> 4 <%# @campaign.content2.try(:) %> 5 <%# @campaign.content2 %> 6 <%= text_field_tag 'campaign[content2][]' %> 7</p> 8 9**new** 10<%= form_for(@campaign) do |f| %> 11 <div class="field"> 12 <%= f.label :title %><br> 13 <%= f.text_field :title %> 14 </div> 15 <div class="field"> 16 <%= f.label :content1 %><br> 17 <%= f.text_field :content1 %> 18 </div> 19 <div class="field"> 20 <%= f.label :content2 %><br> 21 <%= f.text_field :content2 ,{:name => name="campaign[content2][]" ,:multipart => true} %> 22 <%= f.text_field :content2 ,{:name => name="campaign[content2][]" ,:multipart => true} %> 23 </div> 24 <div class="actions"> 25 <%= f.submit %> 26 </div> 27<% end %>
■Controller
**create** def create @campaign = Campaign.new(campaign_params) respond_to do |format| if @campaign.save format.html { redirect_to @campaign, notice: 'Campaign was successfully created.' } format.json { render :show, status: :created, location: @campaign } else format.html { render :new } format.json { render json: @campaign.errors, status: :unprocessable_entity } end end end **Update** def update respond_to do |format| if @campaign.update(campaign_params) format.html { redirect_to @campaign, notice: 'Campaign was successfully updated.' } format.json { render :show, status: :ok, location: @campaign } else format.html { render :edit } format.json { render json: @campaign.errors, status: :unprocessable_entity } end end end **strong parameter** def campaign_params params.require(:campaign).permit(:title, :content1, :content2 => []) end
■model
**db** create_table "campaigns", force: :cascade do |t| t.string "title" t.string "content1" t.string "content2" t.datetime "created_at", null: false t.datetime "updated_at", null: false end **model** class Campaign < ActiveRecord::Base end
そして、入力すると、下記のようにContent2には、「”test","test"]となって、配列で受け取らたように一瞬思いますが、実は配列ではなく文字列でした。
( @campaign.content2として表示しています。そのためgsub等で、”や[等を削除する必要が出てきてしまいます。)
ここからがさらに問題で、この情報を編集しようとすると、下記のようにContent2に入ってしまいます。
どのようにすれば、content2を配列として、格納して、正常に取り出せ、正常にEditできるでしょうか。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/11/12 04:35
2015/11/12 11:01
2015/11/16 01:59