私はモデルUserとGroupとhas_many:throughメソッドを使用するJoinテーブルのメンバシップを持っています。私の参加表のフォームでは、管理者がそのグループのメンバーになるために作成した有効なグループ名を入力する必要があります。ユーザとグループはモデルの検証に参加します
有効な名前が入力されたが、空白のテキストボックスを入力した場合、または入力したグループ名がデータベースに存在する場合、いくつかの妥当性検査が必要な場合があります。 。私はこれがいくつかのバリデーションメソッドによって可能になると思いましたか?
会員部分_form.html.erb
<%= form_for(@membership) do |f| %>
<% if @membership.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@membership.errors.count, "error") %> prohibited this membership from being saved:</h2>
<ul>
<% @membership.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :group %><br />
<%= f.text_field :group %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
membership.rb
class Membership < ActiveRecord::Base
belongs_to :group
belongs_to :user
attr_accessible :user_id, :group_id
validates_uniqueness_of :group_id, :message => "can be only joined once", :scope => 'user_id'
validates_presence_of :group, :user
end
group.rb
class Group < ActiveRecord::Base
has_many :memberships, :dependent => :destroy
has_many :users, :through => :subscriptions
validates :name, :presence => true, :uniqueness => true
attr_accessible :name, :expiry
end
メンバーシップとグループのモデルでは上記の検証が動作しないため、検証が起こるか、私は、データベース内の空のテキストボックスや名前ではないの両方にエラーが出るように
...いくつかの方向性を必要とするCalled id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
編集:
def create
@group = Group.find_by_name(params[:membership][:group])
@membership = current_user.memberships.build(:group_id => @group.id)
respond_to do |format|
if @membership.save
format.html { redirect_to membership_url, :notice => 'Membership was successfully created.' }
format.json { render :json => @membership, :status => :created, :location => @membership }
else
format.html { render :action => "new" }
format.json { render :json=> @membership.errors, :status => :unprocessable_entity }
end
end
end
の下に働く後
これは、グループ名を入力するための検証である私は、空のテキストボックス、またはテキストを投稿するかのように、私は私のメンバーシップ・モデルでは、いくつかの検証をしたいですボックスには存在しない名前がついていますが、それはエラーで失敗します:誤って4になるnilの呼び出しID - 本当にnilのidが必要な場合は、object_idを使用してください。 – Norto23
コントローラコードを投稿できますか? –
createメソッドのコントローラコードが追加されました。 – Norto23