I would like to associate the current_user when I associate this objects on Bar create, another thing, is this way right? Or should I do this on type controller?
Model Bar
belongs_to :type
belongs_to :user
Model Type
has_many :bars
Model User
has_one :bar
Bar Controller
def new
@bar = Bar.new(:type_id => @type.id)
end
def create
@bar = current_user.build_bar(params[:bar].merge(:type_id => @type.id))
if @bar.save
flash.now[:success] = "wohoo!"
render :edit
else
render :new
end
end
The following is the general Rails approach to creating a model through an association – assuming that current_user is set during login or elsewhere and @type is set appropriately in a
before_filter.In the
Bar Controller:Building through the association in this way will automatically set the
user_idfield on bar to thecurrent_user.id.Note also that you will likely want to
redirect_torather thanrenderon the success case. If you want to go to edit directly then userredirect_to edit_bar_path(@bar). If you want to see more info about why then check out the Layouts and Rendering Rails Guide which discusses render v redirect and the implications of each.