Topic: belongs_to , has_many [Solved]

I have to model
1) User
2) Account

I have the User with belongs_to :account
and the Account has_many :users

When i go to Create a User i want to be able to select a account from a drop down menu.

my models
User

class User < ActiveRecord::Base
  belongs_to :account
end 

Account

class Account < ActiveRecord::Base
  has_many :users
end

Controller
user

class UsersController < ApplicationController
  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:success] = "User Created"
      redirect_to @user
    else
      render 'new'
    end
  end
end

view

I am not sure how to call all the Accounts 

Last edited by moiseszaragoza (2012-05-30 16:12:47)

Re: belongs_to , has_many [Solved]

To be able to select an element from a drop-down list, use select view helper (see Rails API):

<%= form_for(@user) do |f| %>
f.select("account_id", Account.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
#or like that:
<%= f.collection_select(:account_id, Account.all, :id, :some_account_attribute, :prompt => true)%>
<%end%>

#You can pass accounts array directly from the controller instead of doing it in the view:
class UsersController < ApplicationController
def new
   @accounts = Account.all.map { |a| [a.name, a.id] }
  @user = User.new
end
end

More details are at Rails guides as well: http://guides.rubyonrails.org/form_help … ith-models

Last edited by Javix (2012-05-30 15:25:10)

Re: belongs_to , has_many [Solved]

Thank you so much