How do I solve this Devise authentication challenge?

走远了吗. 提交于 2020-01-05 06:14:08

问题


Hello people I have some challenges here with devise authentication for users:

I have two models called color and sub_color in my application. the sub_color belongs_to color and color has_many sub_colors.I have already seeded the database with the appropriate data

The challenge; I want a user to be able to chose these in the devise form_for when they are registering as a collection object and the id of the sub_color will be used for identifying a particular user also(a situation where for instance I can sort all the users which cosed blue color). How do I achieve this please?

This is what I have tried but it is not working:

 %= simple_form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
                          <%= f.error_notification %>

                          <div class="form-inputs">
                            <%= f.input :email, required: true, autofocus: true %>
                            <%= f.input :user_name, required: true %>
                            <%= f.input :password, required: true, hint: ("#      {@minimum_password_length} characters minimum" if @minimum_password_length) %>
                            <%= f.input :password_confirmation, required: true %>
                            <%= f.input :first_name, required: true %>

     <%= f.label :color_id, "Color" %> <br/>
     <%= f.collection_select :color_id, Color.order(:name), :id, :name, include_blank: true%>

     <%= f.label :sub_color_id, "Sub Color" %> <br/>
     <%= f.grouped_collection_select :sub_color_id, Color.order(:name), :sub_color, :name, :id, :name, include_blank: true%>

     <div class="form-actions">
                        <%= f.button :submit, "Sign up" %>
                      </div>

model for users:
 belongs_to :sub_color
 has_one :color, through: :sub_color

 devise.......

end


model for sub_color

has_many :users
belongs_to :color

end


model for color

has_many :sub_color

end    

This is the error I see on the web browser

NoMethodError in Devise::Registrations#new
[undefined method `color_id' for #<User:0xbacc720>]

回答1:


Firstly, You need to add color_id and sub_color_id to users table.

Then define association, in user.rb belongs_to :sub_color and in sub_color.rb has_many :users. Same goes with color, user.rb belongs_to :color and in color.rb has_many :users .

Hope that helps!



来源:https://stackoverflow.com/questions/39609816/how-do-i-solve-this-devise-authentication-challenge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!