Rails:通过链接创建关联记录

时间:2014-04-07 18:06:58

标签: ruby-on-rails associations

我有这些模特:

class Users < ActiveRecord::Base      
  has_many  :members
  has_many  :organizations, :through => :members
end

class Organizations < ActiveRecord::Base 
  has_many  :members
  has_many  :users, :through => :members 
end

class Members < ActiveRecord::Base 
 belongs_to :organizations
 belongs_to :users
end

我想创建一个会员记录如下:

  1. 用户登录
  2. 导航到特定组织&#39; show&#39;页
  3. 点击标有&#39;加入&#39;
  4. 的链接

    我已经阅读了网站上的几个帖子,提出了类似的问题;但是,大多数是在同时创建其中一个记录时。这是我尝试过的:

    在我的组织的控制器中,我创建了一个连接方法:

    # PATCH/PUT /organizations/1/join
    def join
      @membership = @organization.members.new(user_id: current_user.id)
      if @membership.save
        flash[:success] = "Your have successfully joined #{@organization.name}!"
        redirect_to @organization
      else
        flash[:error] = "There was an error."
        render 'show'
      end
    end
    

    在我的路线文件中,我添加了一个加入链接:

    resources :organizations do
      member do
        post :join
      end
    end
    

    在我的组织的展示页面上,我添加了如下链接:

    <% if @organization.members.where("user_id = ?", @current_user).exists? %>
      # Unjoin link
    <% else %>
      <%= link_to 'Join!', join_organization_path,
                           :method => "post" %>
    <% end %>
    

    这是我的服务器日志错误:

    Started POST "/organizations/2/join"
    Processing by OrganizationsController#join as HTML
    Parameters: {"authenticity_token"=>"...=", "id"=>"2"}
    Completed 500 Internal Server Error in 1ms
    
    NoMethodError (undefined method `members' for nil:NilClass):
    app/controllers/organizations_controller.rb:47:in `join'
    

    感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

@organization方法中设置实例变量join

def join
  @organization = Organization.find(params[:id]) ## Set @organization
  @membership = @organization.members.new(user_id: current_user.id)
  if @membership.save
    flash[:success] = "Your have successfully joined #{@organization.name}!"
    redirect_to @organization
  else
    flash[:error] = "There was an error."
    render 'show'
  end
end

您收到NoMethodError (undefined method 'members' for nil:NilClass)错误,因为@organization实例变量为nil(未设置)且您在members对象上调用nil方法。

如果您的控制器中设置了before_action回调设置以设置@organization变量,那么您只需添加join作为选项。