【问题标题】:Rails: Associations and reference modelsRails:关联和参考模型
【发布时间】:2016-02-16 22:02:04
【问题描述】:

背景: 我有两个模型User(设计模型)和Client。我已经设置了 Client belongs_to :userUser has_one :client 这样的关联。我已经设置了我的数据库,以便客户端表具有user_id 属性

问题: 在我的导航栏中,一旦用户登录,我希望他们能够访问由Client 模型表示的“个人资料”,但是我似乎无法通过user_params 访问正确的客户端。例如<%= link_to "My Profile", client_path(@user) %>

这会导致错误 No route matches {:action=>"show", :controller=>"clients", :id=>nil} missing required keys: [:id],即使 :id 在用户登录后应该可用。

我已编辑设计 sessions_controller 以包含:

def configure_sign_in_params
  devise_parameter_sanitizer.permit(:sign_up) do |user_params|
    user_params.permit( :email, :password, :id)
  end
end

...但仍然没有运气。我觉得我缺少一些基本的东西,我只是需要一些帮助。

【问题讨论】:

  • 当调用client_path(@user) 时,@usernil。你在你的控制器里设置了吗?也许您打算使用client_path(current_user)
  • 您的routes.rb 文件与用户和客户有关吗?在您的代码 sn-p 中,@user 在控制器中设置为什么?
  • MrYoshi 你是对的!谢谢,那真是个愚蠢的错误-_-。我需要复习我的设计知识

标签: ruby-on-rails devise associations strong-parameters


【解决方案1】:

我缺少一些基本的东西

你不需要@user,它需要是current_user

<%= link_to "Profile", client_path(current_user) if user_signed_in? %>

我们使用类似的模式(User has_one Profile);我们做了一个singular resource,它不需要传递一个对象:

#app/models/user.rb
class User < ActiveRecord::Base
  has_one :client
  accepts_nested_attributes_for :client
end

#config/routes.rb
resource :profile, only: [:show, :update] #-> url.com/profile

#app/controllers/profile_controller.rb
class ProfileController < ApplicationController
  def update
    current_user.update user_params
  end

  private

  def user_params
    params.require(:user).permit(client_attributes: [:x, :y, :z])
  end
end

#app/views/profile/show.html.erb
<%= form_for current_user do |f| %>
  <%= f.fields_for :client do |c| %>
    <%= c.text_field :x %>
  <% end %>
  <%= f.submit %>
<% end %>

这将允许您向...&lt;%= link_to "Profile", profile_path %&gt;发送请求。

因为您只允许每个用户使用 profile 视图,所以您可以为其调用 current_user 对象。

【讨论】:

    猜你喜欢
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    相关资源
    最近更新 更多