Rails : Using jquery tokeninput (railscast #258) to create new entries

后端 未结 2 1090
-上瘾入骨i
-上瘾入骨i 2020-12-30 14:33

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

相关标签:
2条回答
  • 2020-12-30 15:12

    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.

    0 讨论(0)
  • 2020-12-30 15:21

    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.

    0 讨论(0)
提交回复
热议问题