我在Rails中保存数组时遇到了一些麻烦。
Rails version: 4.2.3 | Ruby version: 2.2.1 | DB: PostgreSQL
在我看来,我有一组复选框,显示我的成员参加的会议。
<%= f.fields_for :conferences_member do |conference| %>
<%= collection_check_boxes(:conferences_member, :conference_id, @all_conferences, :id, :name)%>
<% end %>
我在binding.pry
中的创建操作后设置了一个断点(MembersController
),令人惊讶的是,它显示了所选的复选框:
Processing by Database::MembersController#create as HTML
Parameters: {"utf8"=>"✓","authenticity_token"=>"XYZ==",
[...] "conferences_member"=> {"conference_id"=>["3", "5", ""]}, [...]
现在,如果我转到rails c
,并输入ConferencesMember.last
来检查已保存的内容,我会:
pry(main)> ConferencesMember.last
ConferencesMember Load (0.5ms) SELECT "conferences_members".* FROM
"conferences_members" ORDER BY "conferences_members"."id" DESC LIMIT 1
=> nil
这些是我的协会:
#=> member.rb
has_one :conferences_member
accepts_nested_attributes_for :conferences_member, allow_destroy: true, reject_if: :all_blank
#=> conferences_member.rb
serialize :conference_id, Array
belongs_to :member
#=> members_controller.rb
params.require(:member).permit( [...]
:conference_member_attributes => [:id, :member_id, :conference_id => []],
[...])
我想提前感谢你。我在StackOverflow上尝试了几乎所有内容,但我没有看到我的错误。
再次感谢你。
修改
我的更多会员控制器:
def new
@member = Member.new
@member.build_conferences_member
end
def create
@member = Member.new(member_params)
binding.pry
end
日志没有显示任何错误,只显示会议根本没有保存。
答案 0 :(得分:1)
首先,您的字段需要重命名,以便将:conference_id
嵌套在:conferences_member_attributes
中({em>不在:conferences_member
中),就像现在一样。利用fields_for
产生的表单对象:
<%= f.fields_for :conferences_member do |conference| %>
<%= conference.collection_check_boxes :conference_id, @all_conferences, :id, :name %>
<% end %>
您还需要在create
操作中实际保存记录:Member.new
构建记录但不保存。通常,create
操作根据记录是保存还是不保存(由于验证)而分支。所以你可以像这样重写这个方法:
def create
@member = Member.new(member_params)
# when @member.save returns true, it saved to the db successfully
if @member.save
redirect_to members_path, notice: "Member #{@member.id} saved!"
# otherwise, it didn't save because of a validation error, so we render the error
# to the user and give them a chance to fix it
else
flash[:error] = "Member didn't save: #{@member.errors.full_messages.to_sentence}"
render :new
end
end
最后,要确保您的数据通过强参数,请检查日志中是否有过滤掉参数的消息。消息如下:
Unpermitted parameters: your_favorite_attribute