我有两个模特
用户(id,name,is_host,.) 主机(id,name,user_id,.)
与协会
用户hasOne主机
我正在使用Devise注册。当用户希望注册为主机时,我希望将is_host = 1和create a row in Host设置为他在注册表中提供的主机的name。
我想做什么?
register as host时创建关联数据我试图根据用户选择注册的内容在哪里编写逻辑,然后在主机中创建关联行。
用户来自
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.label :first_name %><br />
<%= f.text_field :first_name, autofocus: true %>
</div>
<div class="field">
<%= f.label :last_name %><br />
<%= f.text_field :last_name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email %>
</div>
<div class="field">
<%= f.label :password %>
<% if @validatable %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off" %>
</div>
<div class="field">
<% f.label :password_confirmation %><br />
<% f.password_field :password_confirmation, autocomplete: "off" %>
</div>
<div class="field">
<%= f.label :is_host %><br />
<%= radio_button("user", "is_host", true) %> Yes
<br/>
<%= radio_button("user", "is_host", false) %> No
</div>
<div class="actions">
<%= f.submit "Signup" %>
</div>
<% end %>发布于 2015-04-21 07:40:14
简单的方法是向用户模型中添加一个attr_accessor。
attr_accessor :host_name并在表单中使用这个
= f.text_field :host_name可以根据单选按钮的值在模型中添加after_create回调以保存主机。
after_create :create_user_host, if: Proc.new { |user| user.is_host }
def create_user_host
self.create_host(name: host_name)
end或
您可以使用表格 gem直接保存关联。只需加上
accepts_nested_attributes_for :host在形式上
= nested_form_for resource do |f|
# code for user
= f.fields_for :host do |host_f|
= host_f.text_field :name更多细节可以在表格 gem文档中找到。
希望这能有所帮助!
https://stackoverflow.com/questions/29765409
复制相似问题