【问题标题】:has_many :through broke some codehas_many :through 破坏了一些代码
【发布时间】:2015-06-25 23:26:19
【问题描述】:

所以我对 RoR 比较陌生,并且在尝试让我的代码恢复并正常工作时遇到了一些问题。所以以前我有用户,以及用户可以创建的 wiki。我已经进行了设置,以便用户可以订阅并获得高级状态以将 wiki 设为私有。现在我正在制作它,以便高级用户可以将标准用户作为协作者添加到 wiki。我决定通过 has_many :通过关系将它们关联起来。

我遇到的问题是我的一些按钮开始出现我不理解的错误。我现在遇到的问题是在显示带有创建新 wiki 按钮的页面时。

这是我通过以下方式添加 has_many 时遇到的错误:relationship

No route matches {:action=>"new", :controller=>"wikis", :format=>nil, :user_id=>nil} missing required keys: [:user_id]

以下是模型:

collaborator.rb

class Collaborator < ActiveRecord::Base
  belongs_to :wiki
  belongs_to :user
end

用户.rb

class User < ActiveRecord::Base

  ...

  has_many :collaborators
  has_many :wikis, :through => :collaborators

end

wiki.rb

class Wiki < ActiveRecord::Base

  belongs_to :user

  has_many :collaborators
  has_many :users, :through => :collaborators

end

wiki_controller.rb 的重要部分

def new
  @user = User.find(params[:user_id])
  @wiki = Wiki.new
  authorize @wiki
end

def create
  @user = current_user
  @wiki = @user.wikis.create(wiki_params)
  authorize @wiki
  if @wiki.save
    flash[:notice] = "Wiki was saved"
    redirect_to @wiki
  else
    flash[:error] = "There was an error saving the Wiki. Please try again"
    render :new
  end
end

最后是按钮所在的 show.html.erb 文件。

<div class="center-align">
  <%= link_to "New Wiki", new_user_wiki_path(@user, @wiki), class: 'btn grey darken-1' %>
</div>

如果我缺少任何文件或相关信息,请告诉我。这可能是一个简单愚蠢的答案,但我一生都被困住了。

提前致谢。

编辑:

这里是请求添加的信息,首先在 users_controllers.rb 中显示信息

def show
  @wikis = policy_scope(Wiki)
end

我在 user_policy.rb 中使用的相应策略范围

class UserPolicy < ApplicationPolicy

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      wikis = []
      all_wikis = scope.all
      all_wikis.each do |wiki|
        if wiki.user == user || wiki.users.include?(user)
          wikis << wiki
        end
      end
    end
    wikis
  end

end

还有 route.rb 文件

Rails.application.routes.draw do

  devise_for :users
  resources :users, only: [:update, :show] do
    resources :wikis, shallow: true
  end

  resources :wikis, only: [:index]
  resources :charges, only: [:new, :create]
  delete '/downgrade', to: 'charges#downgrade'

  authenticated do
    root to: "users#show", as: :authenticated
  end

  root to: 'welcome#index'

end

希望对你有帮助

【问题讨论】:

  • 因为它是一个路由错误,包括你的 config/routes.rb 的相关部分会有所帮助。
  • 另外,如果显示模板中发生错误,很高兴看到显示操作。
  • 我已添加所有要求的信息,如果您需要更多信息,请告诉我
  • 当您调用 new_user_wiki_path(@user, @wiki) 时,看起来 @user 为 nil。
  • 在你的控制器中使用before_filter :authenticate_user!

标签: ruby-on-rails ruby activerecord associations


【解决方案1】:

我发现了问题。最初创建协作模型时,我设置了迁移文件错误。

感谢您的所有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    • 2018-02-08
    • 2019-10-30
    相关资源
    最近更新 更多