Ruby on rails Rails:通过链接通过记录创建关联
我有这些模型:Ruby on rails Rails:通过链接通过记录创建关联,ruby-on-rails,associations,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
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
在我的路由文件中,我添加了一个连接链接:
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 %>
谢谢您的帮助。在
join
方法中设置实例变量@organization
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(nil:NilClass的未定义方法'members')
错误,因为@organization
实例变量为nil(未设置),并且您正在调用nil
对象上的members
方法
如果您的控制器中有一个
before\u action
回调设置来设置@organization
变量,那么您可以在其中添加join
作为一个选项。那么这里的问题是什么?什么不起作用?我一直收到闪存错误,而不是闪存成功。当您单击“加入”按钮时,您可以共享生成的服务器日志吗。把它加到问题里。谢谢!这就成功了。我最终只是在我的before_操作:set_organization(private方法)中包含了join方法?我想你的意思是在行动前说。如果这是真的,那么这是更好的方式(添加在答案中),但我没有看到您的问题中共享任何回调相关代码,因此为了更好地解释我在join
操作中设置@organization的问题。
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'
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