Activerecord 在用户存在之前,为“设计注册”中的嵌套\u属性设置用户\u id
这个想法很简单。我需要一个嵌套属性Activerecord 在用户存在之前,为“设计注册”中的嵌套\u属性设置用户\u id,activerecord,ruby-on-rails-4,devise,Activerecord,Ruby On Rails 4,Devise,这个想法很简单。我需要一个嵌套属性标记,用于用户注册标签需要用户id 视图 <%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {role: :form}) do |f| %> <%= f.fields_for :tags, resource.tags.build do |a| %> <%= a.text_field :tagname
标记
,用于用户注册<代码>标签需要用户id
视图
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: {role: :form}) do |f| %>
<%= f.fields_for :tags, resource.tags.build do |a| %>
<%= a.text_field :tagname %>
<% end %>
<% end %>
保存功能目前未被触及。表单传递嵌套属性:tagname刚刚好。但是我无法从资源
获取“将是”的用户id
我已经在网上找了好几个小时的答案了。没有出现任何问题,但是在保存初始用户对象之后应该保存嵌套属性的想法听起来像是一个可行的解决方案。但它不再作为嵌套属性处理
谢谢你的帮助!谢谢 解决方案
好吧,我解决了。我对我的Desive注册控制器做了一点改动,但效果不错
首先,我从标记模型中删除了用户id验证
class Tag < ActiveRecord::Base
belongs_to :user
validates_uniqueness_of :tagname
end
我已经在我的designe locales文件中为错误字符串的翻译定义了:tag_take
和:need_tag
一切正常!
为了记录在案,这是对问题中现有代码的补充
class Tag < ActiveRecord::Base
belongs_to :user
validates_presence_of :user_id
validates_uniqueness_of :tagname
end
class User < ActiveRecord::Base
has_many :tags, autosave: true, dependent: :destroy
accepts_nested_attributes_for :tags
end
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(
:tags_attributes => [:id, :user_id, :tagname]
) }
class Tag < ActiveRecord::Base
belongs_to :user
validates_uniqueness_of :tagname
end
def create
build_resource(sign_up_params)
# added code begins here
@tag = nil
@tag.define_singleton_method(:valid?) {false}
if params["user"].has_key? "tags_attributes"
@tag = Tag.new(params["user"].delete("tags_attributes").values.first)
if @tag.valid?
resource_saved = resource.save # original line of code
else
resource.errors.add(*@tag.errors.first)
flash.delete :tagname_error
set_flash_message :alert, :tag_taken if is_flashing_format?
end
else
set_flash_message :alert, :need_tag if is_flashing_format?
end
# end added code
yield resource if block_given?
if resource_saved
if resource.active_for_authentication?
set_flash_message :notice, :signed_up if is_flashing_format?
sign_up(resource_name, resource)
# This is where current_user has been created and resource.id == current_user.id
# begin added code
@tag.user_id= resource.id
# end added code
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
@validatable = devise_mapping.validatable?
if @validatable
@minimum_password_length = resource_class.password_length.min
end
respond_with resource
end
end