Rails : Using jquery tokeninput (railscast #258) to create new entries
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.
Railscasts #258 jQuery Tokeninput - What about having a form with 4 or 5 tag searchable inputs?
In my application i have 3 different models. This is how i set it up in my application.js:
$(function() {
$("#product_token").tokenInput("/products.json", {
prePopulate: $("#product_token").data("pre"),
tokenLimit: 1
});
});
$(function() {
$("#address_token").tokenInput("/addresses.json", {
prePopulate: $("#address_token").data("pre"),
tokenLimit: 1
});
});
$(function() {
$("#business_token").tokenInput("/businesses.json", {
prePopulate: $("business_token").data("pre"),
tokenLimit: 1
});
});
As you can see, you can treat each individually so you can give your "Author token" more or different options compared to your "Title Token" and "Genre Token".
#258 Token Fields (revised) - how it create new authors?
This code doesn't actually create the author. The authors themselves need to already be created. This code will take the author's tokens, and turn those into IDs. So the Book will have many authors.
You can see in this image below, the authors already exist as the book is being created. We are selecting from the book
image credit: http://railscasts.com/episodes/258-token-fields-revised?view=asciicast
UPDATE
In the end of the episode, the system will create new authors if one is not found. This is created by this code: https://github.com/railscasts/258-token-fields-revised/blob/master/bookstore-tokeninput-after/app/models/author.rb
class Author < ActiveRecord::Base
##...
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
end
So, if the tokens come in with <<>> (which gets sent from the Author.tokens method), it will create the author and then get the ID and return it.
Using jquery tokeninput and acts_as_taggable_on
If you still want to use Jquery TokenInput and add tags there are different ways to do it.
1.
This is actually from my same question; the newest answer: How to use jquery-Tokeninput and Acts-as-taggable-on
This could go in your controller.
def tags
query = params[:q]
if query[-1,1] == " "
query = query.gsub(" ", "")
Tag.find_or_create_by_name(query)
end
#Do the search in memory for better performance
@tags = ActsAsTaggableOn::Tag.all
@tags = @tags.select { |v| v.name =~ /#{query}/i }
respond_to do |format|
format.json{ render :json => @tags.map(&:attributes) }
end
end
This will create the tag, whenever the space bar is hit.
You could then add this search setting in the jquery script:
noResultsText: 'No result, hit space to create a new tag',
It's a little dirty but it works for me.
2.
Check out this guy's method: https://github.com/vdepizzol/jquery-tokeninput
He made a custom entry ability:
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook",
allowCustomEntry: true
});
});
3.
Not to sure about this one but it may help: Rails : Using jquery tokeninput (railscast #258) to create new entries
4.
This one seems legit as well: https://github.com/loopj/jquery-tokeninput/pull/219
I personally like the first one, seems easiest to get and install.
Create new record gets NameError: undefined local variable or method 'through'
You're missing a colon, this:
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings
has_many :questions, through => :taggings
end
should be this:
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings
has_many :questions, :through => :taggings
end
Note that the through
changed to :through
. Just through
is a variable but :through
is a symbol and that's what you usually want for building hashes.
Rails 3: alias_method_chain to set specific attribute first
In your controller, why not just do this:
def create
@post = Post.new :user_id => params[:post][:user_id]
@post.update_attributes params[:post]
...
end
But it seems to me that it would be much better to create the artist records after you've done validation on the post rather than when you first assign the attribute.
EDIT
I would change this to a callback like this:
class Post < ActiveRecord::Base
attr_accessor :author_tokens
def artist_tokens=(tokens)
@artist_tokens = tokens.split(',')
end
after_save :create_artists
def create_artists
@artist_tokens.each do |token|
...
end
end
end
Adding multiple records with duplicate information Rails Ajax?
I installed Nested_forms by ryanb
https://github.com/ryanb/nested_form
This does what I need it to.
Railscast Formtastic
It is incomplete. Check the code (he always upload the code to Github) https://github.com/railscasts/184-formtastic-part-1/blob/master/vet/app/views/animals/show.html.erb
So, instead of:
<p>
<strong>Category:</strong>
<%=h @animal.category_id %>
</p>
Put:
<p>
<strong>Category:</strong>
<%=h @animal.category.name %>
</p>
Use the association of ActiveRecord
Related Topics
Thoughts on Index Creation for SQL Server for Missing Indexes
Sql Server Left Join with 'Or' Operator
How to Optimize Tables for Specific Queries
Are There Reasons for Not Storing Boolean Values in SQL as Bit Data Types
How to Use Group by Based on a Case Statement in Oracle
Sql Server - Return Schema for Sysobjects
Rails Brakeman Warning of SQL Injection
If I Update a View, Will My Original Tables Get Updated
Get Total Row Count While Paging
Is Count(*) in SQL Server a Constant Time Operation? If Not, Why Not
Sql Server 2012 Sp_Helptext Extra Lines Issue
How to Calculate Average of a Column and Then Include It in a Select Query in Oracle
Could Not Find Server 'server Name' in Sys.Servers. SQL Server 2014
How Gremlin Query Same SQL Like for Search Feature
Writing a Function in SQL to Loop Through a Date Range in a Udf