I have 2 models, users, and common_apps.
users has_one :common_app.
Before this, I wrote the code as the users has_many common_apps, however I'm not sure how to rewrite that for a has_one association. The main confusion is how to structure 'new' in common_app controller.
When I try, I get an undefined method error.
undefined method `new' for #<CommonApp:>
This is my code -->
def new
if current_user.common_app.any?
redirect_to current_user
else
@common_app = current_user.common_app.new
end
end
def create
@common_app = current_user.common_app.build(common_app_params)
if @common_app.save
flash[:success] = "Common App Created!"
redirect_to root_url
else
redirect_to 'common_apps/new'
end
end
def show
@common_apps = current_user.common_app
end
how would you restructure this, if this were to be a has_one association?
I think I know how the 'create' one should be -->
def create
@common_app = current_user.build_common_app(common_app_params)
if @common_app.save
flash[:success] = "Common App Created!"
redirect_to root_url
else
redirect_to 'common_apps/new'
end
end
Your new action should look like this:
def new
if current_user.common_app.present?
redirect_to current_user
else
@common_app = current_user.build_common_app
end
end
You can also call build_common_app
without any parameters passed to it, which will initialize an empty CommonApp for current_user
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.