ruby on rails - Setting attribute in join model when creating two new parents -


i have 2 models: user , company. company can have many users , user can have many companies. might suggest, perfect place use join table. i'm using full blown model join user , company can specify role each user has. table, companies_users, therefore has following columns: user_id, company_id , company_role.

the situation i'm trying negotiate 1 in i'm creating both company , user , specify company_role while doing so.

my new method follows:

def new     @user=user.new     @company=@user.companies.build end 

this creates entry in companies_users join table (obviously) in leaving company_role blank.

how might add bit of info?

thanks in advance!

you can pass attributes through build / create methods:

#app/controllers/users_controller.rb class userscontroller < applicationcontroller     def new        @user = user.new        @user.company_users.build.build_company     end      def create        @user = user.new user_params        @user.save       end      private      def user_params        params.require(:user).permit(company_users_attributes: [company_attributes:[:name]])     end end  #app/views/users/new.html.erb <%= form_for @user |f| %>    <%= f.fields_for :company_users |cu| %>        <%= cu.text_field :company_role %>        <%= cu.fields_for :company |c| %>           <%= c.text_field :name %>        <% end %>    <% end %>    <%= f.submit %> <% end %> 

the above looks complicated, i'll explain in second.

you need following models:

#app/models/user.rb class user < activerecord::base    has_many :company_users    has_many :companies, through: :company_users    accepts_nested_attributes_for :company_users end  #app/models/company_user.rb class companyuser < activerecord::base    belongs_to :company    belongs_to :user    accepts_nested_attributes_for :company end  #app/models/company.rb class company < activerecord::base    has_many :company_users    has_many :users, through: :company_users end 

if want create company and company_user, you'll have pass params both. although looks messy, you're doing passing each nested object respective models.

if want set "role", have pass attributes company_users. if want create new company (rather assigning existing one), need pass respective params too.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -