Reputation: 411
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?
belongs_to :type
belongs_to :user
has_many :bars
has_one :bar
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
Upvotes: 0
Views: 134
Reputation: 9604
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
:
def new
@bar = current_user.bar.build
end
def create
@bar = current_user.bar.build(params[:bar].merge(:type_id => @type.id))
if @bar.save
flash.now[:success] = "wohoo!"
redirect_to @bar
else
render :new
end
end
Building through the association in this way will automatically set the user_id
field on bar to the current_user.id
.
Note also that you will likely want to redirect_to
rather than render
on the success case. If you want to go to edit directly then user redirect_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.
Upvotes: 1