Ryan Bates railscast #258 http://railscasts.com/episodes/258-token-fieldsに含まれていなかった新しいアーティスト エントリの追加を正常に実装できました。
つまり、ユーザーは jquery tokinput を使用してオートコンプリートされるアーティスト名を入力できます。ただし、オートコンプリートの結果には、その個々のユーザーによって作成されたアーティスト名のみが表示されるようにしたいと考えています。
これは理にかなっていますか?より適切でわかりやすい例は、ユーザーが投稿を作成し、投稿が属する「コレクション」を指定する collection.rb の場合ですが、自分で作成したコレクションにのみ投稿を追加できる必要があります。
これは、仮想属性として artist_tokens を使用した投稿フォームです。
<%= form_for @post, :validate => true, :html => {:multipart => true} do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :title, 'Title:' %><br />
<%= f.text_field :title %><br />
<%= f.label :artist_tokens, "Artists" %><br />
<%= f.text_field :artist_tokens, "data-pre" =>
@post.artists.map(&:attributes).to_json %>
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
これは、投稿フォームの artist_tokens フィールドに入力された値によってアーティストを検索し、新しいエントリを追加するオプション「{params[:q]} を追加」も追加しました。
class ArtistsController < ApplicationController
def index
@artists = Artist.where("name like ?", "%#{params[:q]}%")
results = @artists.map(&:attributes)
results << {:name => "Add: #{params[:q]}", :id => "CREATE_#{params[:q]}_END"}
respond_to do |format|
format.html
format.json { render :json => results }
end
end
「新しい」エントリを ID で解析し、それらを使用して新しいアーティストを作成する追加のコードを追加しました。次に、artist_ids が再度割り当てられます。
post.rb
def artist_tokens=(ids)
ids.gsub!(/CREATE_(.+?)_END/) do
Artist.create!(:name => $1).id
end
self.artist_ids = ids.split(",")
end
current_user のエントリのみによって json の結果を絞り込む機能を除いて、すべてがうまく機能します。どうすればこれを行うことができますか?エントリ作成者の user_id をテーブルに保存する必要がありますか? これどうやってするの?
編集: モデルの関連付け
# app/models/user.rb
class User < ActiveRecord::Base
has_many :posts
has_many :artists, :through => :posts
end
# app/models/post.rb
class Post < ActiveRecord::Base
belongs_to :user
has_many :artisanships
has_many :artists, :through => :artisanships
end
# all/models/artist.rb
class Artist < ActiveRecord::Base
has_many :artisanships
has_many :users, :through => :artisanships
has_many :posts, :through => :artisanships
end
# app/models/artisanship.rb
class Artisanships < ActiveRecord::Base
belongs_to :post
belongs_to :artist
has_one :user, :through => :post
end
編集: posts_controller.rb
class PostsController < ApplicationController
before_filter :authenticate_user!, :only => [:create, :edit, :update, :destroy]
before_filter :authorized_user, :only => [:destroy, :edit, :update]
def create
@user = current_user
@post = current_user.posts.build(params[:post])
if @post.save
flash[:success] = "Post created!"
redirect_to root_path
else
@feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page])
render 'pages/home'
end
end
def index
@posts = Post.paginate(:page => params[:page])
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
respond_to do |format|
if @post.update_attributes(params[:post])
format.html { redirect_to(post_path(@post), :notice => 'Post was successfully updated.') }
else
format.html { render :action => "edit" }
end
end
end
def destroy
@post.destroy
redirect_to root_path
end
def likers
@title = "Likers"
@post = Post.find(params[:id])
@likers = @post.likers.paginate(:page => params[:page])
render 'show_likers'
end
def search
if params[:q]
query = params[:q]
@search = Post.search do
keywords query
end
@posts = @search.results
end
end
private
def authorized_user
@post = Post.find(params[:id])
redirect_to root_path unless current_user?(@post.user)
end
編集: 投稿の user_id 属性を最初に設定するために alias_method_chain を試みました。(NULL db エントリを修正するために動作しませんでした) 参照先: Rails 3: alias_method_chain still used?
def attributes_with_user_id_first=(attributes = {})
# Make sure not to accidentally blank out the important_attribute when none is passed in
if attributes.include?(:user_id)
self.user_id = attributes.delete(:user_id)
end
self.attributes_without_user_id_first = attributes
end
alias_method_chain :attributes=, :user_id_first