テキスト フィールドを使用してユーザーの電子メールを検索し、見つかった場合はメンバーシップを作成しようとしています。見つからない場合は、メールアドレスに基づいてユーザーを作成したいと思います。
メンバーシップ/Index.html.erb
<%= render :partial => 'shared/logedinNav' %>
<section class="centered">
<header>Team Settings</header>
<section class="main">
<aside class="blue_nav_aside">
<nav>
<ul>
<li><%= link_to_unless_current "General", team_info_path(:id => @team.id) %></li>
<li id="bluenav"><%= link_to_unless_current "Team Members", memberships_path(:id => @team.id) %></li>
<li><%= link_to_unless_current "Tags & Categories", %></li>
<li><%= link_to_unless_current "Payments", %></li>
</ul>
</nav>
</aside>
<section class="inline_form">
<%= form_for @membership do |u|%>
<% if notice %>
<p id="notice"><%= notice %></p>
<% end %>
<% if alert %>
<p id="alert"><%= alert %></p>
<% end %>
<%= render "shared/error_messages", :target => @membership %>
<%= u.hidden_field :team_id, :value => @team.id %>
<h1><span class="pictos pictos-form-h1">g</span>Team Members</h1>
<%= u.text_field :user_email, :placeholder => " To add a team member, enter their email here..." %>
<%= u.submit "Invite", :class => "grey button" %>
<section>
<ul>
<% @memberships.each do |m|%>
<li>
<%= m.user.email %>
<% if m.team.admin_user_id != m.user_id %>
<%= link_to(membership_path(m), :confirm => 'Are you sure you want to delete this video?', :method => :delete, :class => "red_link") do %>
<span class="pictos pictos-remove">-</span> Remove
<% end %>
<% end %>
</li>
<% end %>
</ul>
</section>
<% end %>
</section>
</section>
Memberships_controller.rb
class MembershipsController < ApplicationController
def index
@team = Team.find(params[:id])
@memberships = Membership.where(:team_id => @team.id)
@membership = Membership.new
end
def create
@membership = Membership.new(params[:membership])
@team = Team.find(params[:membership][:team_id])
@membership.user = User.find_or_create_by_email(:email => params[:membership][:user_email], :password => "pass", :password_confirmation => "pass")
if @membership.save
redirect_to memberships_path(:id => @team.id), :notice => "New membership created."
else
redirect_to memberships_path(:id => @team.id), :alert => "Fail."
end
end
....
end
メンバーシップ.rb
class Membership < ActiveRecord::Base
belongs_to :team
belongs_to :user
accepts_nested_attributes_for :user
attr_accessible :user_id, :team_id
attr_accessor :user_email
validates_presence_of :user_id, on: :create
after_create :set_team_admin
def set_team_admin
self.team.set_admin_user
end
end
ユーザーが見つかったときに機能しますが、現在はまったく認識せずcreate_user
、Fail リダイレクトにスキップします。
更新: これは、以下に示す提案を含む更新されたコードです。