开发者

how to insert same data into two tables using nested forms

I am using nested forms to insert data into two tables (user and address).I want to have my users email id in both the table, but the user should enter the email id once. Here is my current view

<%= form_for @user do |f| %>
  <%= f.text_field(:name, :size => 20) %>
  <%= f.text_field(:email, :size => 20) %>

    <%= f.fields_for :address do |r| %>
      <%= r.text_field(:street, :size => 20) %>
      <%= r.text_field(:city, :size => 20) %>
    <% end %>
   <%= f.submit "Create" %>
<% end %>

In my nested section "address" i once again want the email field, but i don't want a repeated text field for email. How can i use the email section inside the nested form "address"? I have tried using hidden form fields, but it didn't worked. Can somebody help please.

EDIT

Controller(Only question related parts)

class UsersController < ApplicationController
 def new       
   @domain = Domain.find(params[:id])
   @user = @domain.users.build
   @title = "Add User"
 end
 def create
   @user = User.new(params[:user])
   if @user.save
    flash[:success] = "Welcome!"
    redirect_to manageDomain2_path(:id => @user.domain_id)
  else
    @title = "Add User"
    redirect_to addNewUser_path(:id => @user.domain_id)
 end
end

I have tried with:

@user = User.new(params[:user][:address_attributes].merge!(:email => params[:user][:email]))

When using:

@user = User.new(params[:user][:address].merge!(:email => params[:user][:email]))

I am getting error "Undefined method merge".

User Model (Question related portion only)

class User < ActiveRecord::Base
   attr_accessible: :email, :domain_id, :address_attributes

   belongs_to :domain
   has_one :address

   accepts_nested_attributes_for :address
end

Address Model (Full)

class Address < ActiveRecord::Base
   attr_accessible :user_id, :email, :street, :city

end

When i use

belo开发者_StackOverflow中文版ngs_to :user

in address model i get syntax error. So i have tried without using it. the user_id, street, city is getting proper values but email email field is not getting any thing.


You can just add it to the params hash from your controller:

params[:user][:address].merge!(:email =>  params[:user][:email])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜