Hi Guys I have a Relationships in Mongoid and I can not add current_user to this relation for get the user that create the deal. A relation with 3 model.
I have three models user.rb, house.rb and deal.rb
user.rb Relationships (devise model)
# Relationships
has_many :houses, dependent: :destroy
has_many :deals, dependent: :destroy
key :title
house.rb
# Relationships
belongs_to :user
embeds_many :deals
deal.rb
# Relationships
embedded_in :house, :inverse_of => :deals
belongs_to :user
In my routes.rb
resources :houses do
resources :deals
end
In my houses_controller.rb in my create method I get current_user for each house of this side:
def create
#@house = House.new(params[:house])
@house = current_user.houses.new(params[:house])
respond_to do |format|
if @house.save
format.html { redirect_to @house, notice: 'House was successfully created.' }
format.json { render json: @house, status: :created, location: @house }
else
format.html { render action: "new" }
format.json { render json: @house.errors, status: :unprocessable_entity }
end
end
end
In my deals_controller.rb I have the created method this:
def create
@house = House.find_by_slug(params[:house_id])
@user = User.find(:user_id)
@deal = @house.deals.create!(params[:deal])
redirect_to @house, :notice => "Comment created!"
end
How I can add to this last method create, the current_user that created the deal?
You can simply add these two lines to the create action:
And I would also suggest you not to use create! instead you should use .new and .save like in the scaffolded create actions! 😉