I have successfully been able to implement the addition of new artist entries which was not included in Ryan Bates railscast #258 http://railscasts.com/episodes/258-token-fi
If you don't want to modify anything in your models, then you can do it like this:
def index
@artists = current_user.posts.join("artisianships").join("artists").
where("artisianships.post_id = posts.id").
where("artists.name like ?", "#{params[:q]}").
select("artists.name as name, artists.id as id")
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
Notice that there are a lot of joins going on here, so not recommended.
To debug why Artist.create!(:name => $1, :user_id => self.user_id)
would not work, it would be great if we can see some more code, particularly the action
to create a Post
UPDATE: Did you try changing PostController#create
to following, although I feel curent code should work as it is,
@post = current_user.posts.build
if @post.update_attributes(params[:post])
# do something
else
# do something else
end
I am not a rails pro and don't understand the alias_method_chain
so can't comment on why it didn't work.
if you're using some authentication solution like devise, clearance or authlogic, you probably already have current_user method. Therefore add a column user_id:integer to the Artist model and do the following:
#User model
has_many :artists
#Artist model
belongs_to :user
#Artists controller
def index
@artists = current_user.artists.where("name like ?", "%#{params[:q]}%") #this answers your question!
... blah blah
end
And of course do not forget to set the user_id column when you create an artist.