change rails association from has_many to has_one












0















I'm trying to change my model association from a has_many (which works) to a has_one but I'm running into issues.



when i go to:



localhost:3000/users/1/security_badge/new


i get this in the logs



NoMethodError (undefined method `new' for nil:NilClass):


User model:



class User < ApplicationRecord
has_one :security_badge, dependent: :destroy
end


SecurityBadge model:



class SecurityBadge < ApplicationRecord    
belongs_to :user
end


my routes:



  resources :users do
resource :security_badge
end


some of my controller security_badges_controller:



  before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
before_action :set_security_badge, only: [:show, :edit, :update, :destroy]

def new
@security_badge = @user.security_badge.new
end

def edit
end

def create
@security_badge = @user.security_badge.new(security_badge_params)

respond_to do |format|
if @security_badge.save
format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
else
format.html { render :new }
end
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:user_id])
end

def set_security_badge
@security_badge = SecurityBadge.find(params[:id])
end


Update



this is in my _form:



<%= form_with(model: [@user, security_badge], local: true) do |form| %>
<% if security_badge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>

<ul>
<% security_badge.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= form.label :name %>
<%= form.text_field :name, autofocus:true, class: "form-control" %>
</div>

<br>
<div class="row float-right">
<div class="col-md-12 actions">
<%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
<%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
</div>
</div>

<% end %>


new view template:



<%= render 'form', security_badge: @security_badge %>









share|improve this question

























  • Do you have before_action :set_user?

    – Neodelf
    Nov 25 '18 at 20:05











  • check if you have callback method before_action :set_user on your SecurityBadgesController

    – John Baker
    Nov 25 '18 at 20:16











  • yes i have the before actions, just updated the question with it. thanks

    – random_user_0891
    Nov 25 '18 at 20:29
















0















I'm trying to change my model association from a has_many (which works) to a has_one but I'm running into issues.



when i go to:



localhost:3000/users/1/security_badge/new


i get this in the logs



NoMethodError (undefined method `new' for nil:NilClass):


User model:



class User < ApplicationRecord
has_one :security_badge, dependent: :destroy
end


SecurityBadge model:



class SecurityBadge < ApplicationRecord    
belongs_to :user
end


my routes:



  resources :users do
resource :security_badge
end


some of my controller security_badges_controller:



  before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
before_action :set_security_badge, only: [:show, :edit, :update, :destroy]

def new
@security_badge = @user.security_badge.new
end

def edit
end

def create
@security_badge = @user.security_badge.new(security_badge_params)

respond_to do |format|
if @security_badge.save
format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
else
format.html { render :new }
end
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:user_id])
end

def set_security_badge
@security_badge = SecurityBadge.find(params[:id])
end


Update



this is in my _form:



<%= form_with(model: [@user, security_badge], local: true) do |form| %>
<% if security_badge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>

<ul>
<% security_badge.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= form.label :name %>
<%= form.text_field :name, autofocus:true, class: "form-control" %>
</div>

<br>
<div class="row float-right">
<div class="col-md-12 actions">
<%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
<%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
</div>
</div>

<% end %>


new view template:



<%= render 'form', security_badge: @security_badge %>









share|improve this question

























  • Do you have before_action :set_user?

    – Neodelf
    Nov 25 '18 at 20:05











  • check if you have callback method before_action :set_user on your SecurityBadgesController

    – John Baker
    Nov 25 '18 at 20:16











  • yes i have the before actions, just updated the question with it. thanks

    – random_user_0891
    Nov 25 '18 at 20:29














0












0








0








I'm trying to change my model association from a has_many (which works) to a has_one but I'm running into issues.



when i go to:



localhost:3000/users/1/security_badge/new


i get this in the logs



NoMethodError (undefined method `new' for nil:NilClass):


User model:



class User < ApplicationRecord
has_one :security_badge, dependent: :destroy
end


SecurityBadge model:



class SecurityBadge < ApplicationRecord    
belongs_to :user
end


my routes:



  resources :users do
resource :security_badge
end


some of my controller security_badges_controller:



  before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
before_action :set_security_badge, only: [:show, :edit, :update, :destroy]

def new
@security_badge = @user.security_badge.new
end

def edit
end

def create
@security_badge = @user.security_badge.new(security_badge_params)

respond_to do |format|
if @security_badge.save
format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
else
format.html { render :new }
end
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:user_id])
end

def set_security_badge
@security_badge = SecurityBadge.find(params[:id])
end


Update



this is in my _form:



<%= form_with(model: [@user, security_badge], local: true) do |form| %>
<% if security_badge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>

<ul>
<% security_badge.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= form.label :name %>
<%= form.text_field :name, autofocus:true, class: "form-control" %>
</div>

<br>
<div class="row float-right">
<div class="col-md-12 actions">
<%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
<%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
</div>
</div>

<% end %>


new view template:



<%= render 'form', security_badge: @security_badge %>









share|improve this question
















I'm trying to change my model association from a has_many (which works) to a has_one but I'm running into issues.



when i go to:



localhost:3000/users/1/security_badge/new


i get this in the logs



NoMethodError (undefined method `new' for nil:NilClass):


User model:



class User < ApplicationRecord
has_one :security_badge, dependent: :destroy
end


SecurityBadge model:



class SecurityBadge < ApplicationRecord    
belongs_to :user
end


my routes:



  resources :users do
resource :security_badge
end


some of my controller security_badges_controller:



  before_action :set_user, only: [:index, :show, :new, :edit, :create, :update]
before_action :set_security_badge, only: [:show, :edit, :update, :destroy]

def new
@security_badge = @user.security_badge.new
end

def edit
end

def create
@security_badge = @user.security_badge.new(security_badge_params)

respond_to do |format|
if @security_badge.save
format.html { redirect_to user_security_badge_path(@security_badge.user), notice: 'Security badge was successfully created.' }
else
format.html { render :new }
end
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:user_id])
end

def set_security_badge
@security_badge = SecurityBadge.find(params[:id])
end


Update



this is in my _form:



<%= form_with(model: [@user, security_badge], local: true) do |form| %>
<% if security_badge.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(security_badge.errors.count, "error") %> prohibited this security_badge from being saved:</h2>

<ul>
<% security_badge.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>

<div class="field">
<%= form.label :name %>
<%= form.text_field :name, autofocus:true, class: "form-control" %>
</div>

<br>
<div class="row float-right">
<div class="col-md-12 actions">
<%= link_to "Cancel", user_path(@security_badge.user), id: 'cancel', class: 'btn btn-outline-secondary' %>
<%= form.submit "Submit", id: "submit", class: 'btn btn-success' %>
</div>
</div>

<% end %>


new view template:



<%= render 'form', security_badge: @security_badge %>






ruby-on-rails ruby-on-rails-5






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 23:22







random_user_0891

















asked Nov 25 '18 at 19:00









random_user_0891random_user_0891

5511417




5511417













  • Do you have before_action :set_user?

    – Neodelf
    Nov 25 '18 at 20:05











  • check if you have callback method before_action :set_user on your SecurityBadgesController

    – John Baker
    Nov 25 '18 at 20:16











  • yes i have the before actions, just updated the question with it. thanks

    – random_user_0891
    Nov 25 '18 at 20:29



















  • Do you have before_action :set_user?

    – Neodelf
    Nov 25 '18 at 20:05











  • check if you have callback method before_action :set_user on your SecurityBadgesController

    – John Baker
    Nov 25 '18 at 20:16











  • yes i have the before actions, just updated the question with it. thanks

    – random_user_0891
    Nov 25 '18 at 20:29

















Do you have before_action :set_user?

– Neodelf
Nov 25 '18 at 20:05





Do you have before_action :set_user?

– Neodelf
Nov 25 '18 at 20:05













check if you have callback method before_action :set_user on your SecurityBadgesController

– John Baker
Nov 25 '18 at 20:16





check if you have callback method before_action :set_user on your SecurityBadgesController

– John Baker
Nov 25 '18 at 20:16













yes i have the before actions, just updated the question with it. thanks

– random_user_0891
Nov 25 '18 at 20:29





yes i have the before actions, just updated the question with it. thanks

– random_user_0891
Nov 25 '18 at 20:29












1 Answer
1






active

oldest

votes


















3














Use @user.build_security_badge (method provided by the has_one association macro) instead of @user.security_badge.new (security_badge is nil, that's why you get an error).



https://guides.rubyonrails.org/association_basics.html#has-one-association-reference






share|improve this answer
























  • thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

    – random_user_0891
    Nov 25 '18 at 23:27













  • updated the question with my form and new templates. not sure how that path is getting generated though.

    – random_user_0891
    Nov 25 '18 at 23:29











  • the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

    – random_user_0891
    Nov 26 '18 at 1:19











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470863%2fchange-rails-association-from-has-many-to-has-one%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









3














Use @user.build_security_badge (method provided by the has_one association macro) instead of @user.security_badge.new (security_badge is nil, that's why you get an error).



https://guides.rubyonrails.org/association_basics.html#has-one-association-reference






share|improve this answer
























  • thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

    – random_user_0891
    Nov 25 '18 at 23:27













  • updated the question with my form and new templates. not sure how that path is getting generated though.

    – random_user_0891
    Nov 25 '18 at 23:29











  • the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

    – random_user_0891
    Nov 26 '18 at 1:19
















3














Use @user.build_security_badge (method provided by the has_one association macro) instead of @user.security_badge.new (security_badge is nil, that's why you get an error).



https://guides.rubyonrails.org/association_basics.html#has-one-association-reference






share|improve this answer
























  • thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

    – random_user_0891
    Nov 25 '18 at 23:27













  • updated the question with my form and new templates. not sure how that path is getting generated though.

    – random_user_0891
    Nov 25 '18 at 23:29











  • the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

    – random_user_0891
    Nov 26 '18 at 1:19














3












3








3







Use @user.build_security_badge (method provided by the has_one association macro) instead of @user.security_badge.new (security_badge is nil, that's why you get an error).



https://guides.rubyonrails.org/association_basics.html#has-one-association-reference






share|improve this answer













Use @user.build_security_badge (method provided by the has_one association macro) instead of @user.security_badge.new (security_badge is nil, that's why you get an error).



https://guides.rubyonrails.org/association_basics.html#has-one-association-reference







share|improve this answer












share|improve this answer



share|improve this answer










answered Nov 25 '18 at 20:53









arieljuodarieljuod

6,54711121




6,54711121













  • thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

    – random_user_0891
    Nov 25 '18 at 23:27













  • updated the question with my form and new templates. not sure how that path is getting generated though.

    – random_user_0891
    Nov 25 '18 at 23:29











  • the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

    – random_user_0891
    Nov 26 '18 at 1:19



















  • thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

    – random_user_0891
    Nov 25 '18 at 23:27













  • updated the question with my form and new templates. not sure how that path is getting generated though.

    – random_user_0891
    Nov 25 '18 at 23:29











  • the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

    – random_user_0891
    Nov 26 '18 at 1:19

















thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

– random_user_0891
Nov 25 '18 at 23:27







thanks but I'm getting a weird error when I use @user.build_security_badge saying ActionView::Template::Error (undefined method user_security_badges_path for .... which is kind of good because now it means that security_badge is no longer nil, but I can't find that pluralized path anywhere. notice it says security_badges with an s instead of user_security_badge_path

– random_user_0891
Nov 25 '18 at 23:27















updated the question with my form and new templates. not sure how that path is getting generated though.

– random_user_0891
Nov 25 '18 at 23:29





updated the question with my form and new templates. not sure how that path is getting generated though.

– random_user_0891
Nov 25 '18 at 23:29













the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

– random_user_0891
Nov 26 '18 at 1:19





the template error was due to having a nested form and using a singular resource route, for anyone who may have the same issue in the future here's more details on how to get a singular route with a nested form stackoverflow.com/questions/53473476/…

– random_user_0891
Nov 26 '18 at 1:19


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470863%2fchange-rails-association-from-has-many-to-has-one%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Contact image not getting when fetch all contact list from iPhone by CNContact

count number of partitions of a set with n elements into k subsets

A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks