My Rails 4应用程序是骑自行车的筹款工具。用户可以创建RiderReg(istration),用户也有一个关联的MailingAddress,通过RiderReg委托给用户。
这些关联似乎在控制台中工作,但是我被强大的params抛出,并且控制器不会接受RiderReg的MailingAddress的嵌套属性 - 因为MailingAddress与User关联。
您可能想知道 - 为什么用户和骑手会分开模型?因为用户可以是捐赠者和/或骑手 - 但是所有用户无论是骑手还是否都需要地址。
ANYHOO - 让我添加一些代码示例。
class RiderReg < ActiveRecord::Base
belongs_to :rider, :class_name => "User"
delegate :first_name, :last_name, :title, :full_name, :receipts, :mailing_address, to: :rider, allow_nil: true, prefix: false
# accepts_nested throws an error - but how else to allow for strong params?
accepts_nested_attributes_for :mailing_address
end
class User < ActiveRecord::Base
has_one :rider_reg, :foreign_key => :rider_id
has_one :mailing_address, :as => :addressable
accepts_nested_attributes_for :mailing_address
end
class RiderRegsController < ApplicationController
private
def rider_reg_params
params.require(:rider_reg).permit(:ride_option, :primary_phone, :secondary_phone, :birthdate, :goal, :bio, :accept_terms, :photo, :mailing_address_attributes => [:line1, :line2, :city, :state, :zip])
end
end
通过form_helper提交的我的Params哈希看起来像这样:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"PbDQe/f4S+dlhroY+ZDVh6MS0Mmo0fUr88UiE4OJJQQ=", "rider_reg"=>{"ride_option"=>"Original Track", "mailing_address"=>{"line1"=>"asdfasfd", "line2"=>"", "city"=>"asdfsadf", "state"=>"Alaska", "zip"=>""}, "primary_phone"=>"", "secondary_phone"=>"", "bio"=>"", "goal"=>"0.0"}, "rider_reg_month"=>"1", "rider_reg_year"=>"1934", "rider_reg_day"=>"1", "commit"=>"Create Rider reg"}
我的服务器日志告诉我:
Unpermitted parameters: mailing_address
所以 - 经过几天的轰炸 - 我认为现在可能是时候承认我的无知了。任何建议都非常感谢! 谢谢!
答案 0 :(得分:1)
因为RiderReg和MailingAddress之间没有关联。
有两种方法可以解决这个问题。
RiderReg
和MailingAddress
切换RiderReg
和rider
关系以及外键。然后接受rider
的嵌套属性,并将视图视为:
= f.fields_for :rider do |uf|
# user fields here.
= uf.fields_for :mailing_address do |maf|
# mailing address fields here
然后调整强力参数以接受用户。