正确地在用户和组之间创建联接操作

时间:2012-02-08 04:17:32

标签: ruby-on-rails-3

尝试根据用户在会员资格表格中输入的名称为用户创建会员资格时遇到问题 - new.html.erb。

user.rb

  has_many :memberships, :dependent => :destroy
  has_many :groups, :through => :memberships

membership.rb

class Membership < ActiveRecord::Base
  attr_accessible :user_id, :group_id
  belongs_to :user
  belongs_to :group
end

group.rb

  has_many :memberships, :dependent => :destroy
  has_many :users, :through => :memberships

会员控制

  def create
      @group = Group.find_by_name(:group)
      @membership = current_user.memberships.build(:group_id => @group.group_id)
      if @membership.save
        flash[:notice] = "You have joined this group."
        redirect_to :back
      else
        flash[:error] = "Unable to join."
        redirect_to :back
      end
    end

成员资格 - _form.html.erb

<%= form_for(@membership) do |f| %>
  ...
  #error validation
  ...

  <div class="field">
    <%= f.label :group %><br />
    <%= f.text_field :group %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我想要它做的是找到输入的组(如果存在),并相应地在成员资格表中创建表条目。只是不确定我正在做的是在正确的轨道上。有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您的代码现在无法正常工作的原因是:

@group = Group.find_by_name(:group)

它应该是(我不记得确切对不起)

@group = Group.find_by_name(params[:membership][:group])

错误在下一行被调用,因为@groupnil

但是你应该使用虚拟属性或其他东西处理模型中的那种逻辑。

<强> membership.rb

def group_name
  if self.group
    @group_name ||= self.group.name
  end
end

def group_name=(group_name)
  @group_name = group_name

  self.group = Group.find_by_name(@group_name)
end

<强>形式

<div class="field">
  <%= f.label :group_name, "Group" %><br />
  <%= f.text_field :group_name %>
</div>

<强>控制器

def create
  @membership = current_user.memberships.build(params[:membership])
  if @membership.save
    flash[:notice] = "You have joined this group."
    redirect_to :back
  else
    flash[:error] = "Unable to join."
    redirect_to :back
  end
end