0

レールスクールに精通していれば、#258トークンフィールドに続いて最初にこれを設定しています。ライアンは書籍を所有していますが、著者は著作権を所有しています。 。 (ユーザーbelong_toと投稿)http://asciicasts.com/episodes/258-token-fieldsRails 3:このリクエストのMVCを理解できない問題

だから、他の言葉で:

私はフィールドのタイトルやアーティストとユーザーの作成投稿があり、投稿フォームがartist_tokensと呼ばれるアーティストフィールドの仮想属性が含まれ、この仮想属性がありartist_tokens =(ids)という関連するセッターメソッド。

これは私に問題を理解させる方法です。このメソッドは2つのことを行います。投稿フォームに入力されたIDを取り、Artist.createを呼び出します。 :の名前としてIDを使用します。次に、残っているアーティストオブジェクトに応じて.idを呼び出します。これはartisanship associationを作成するために使用されるartist_idです。

1)投稿モデルの中からArtist.create(:name => $ 1)を呼び出すとどうなりますか?

2)その要求は、アーティストコントローラ内のcreateメソッドに移動しますか?

通常の投稿要求はpostscontroller#createメソッドに行き、その後データベースに書き込んだ後、post_pathなどの作成メソッド内のどのパスにでもリダイレクトするので、postscontroller#showにヒットしてからビューに。正しい?

3)Artist.createを呼び出すときに私が行っていることを見るためにコントローラからモデルへの要求のシーケンスは何ですか?ポストモデル内のartist_tokens =(ids)メソッドから?

# app/models/user.rb 

class User < ActiveRecord::Base 
    has_many :posts, :dependent => :destroy 
    has_many :artists, :through => :posts 
    attr_accessible :email, :password, :password_confirmation, 
        :remember_me, :name, :avatar, :username, :bio 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 
    mount_uploader :avatar, AvatarUploader  

end 



# app/models/post.rb 

class Post < ActiveRecord::Base 

    belongs_to :user 
    has_many :artisanships 
    has_many :artists, :through => :artisanships 
    attr_accessible :title, artist_tokens 
    attr_reader :artist_tokens 

    def artist_tokens=(ids) 
    ids.gsub!(/CREATE_(.+?)_END/) do 
     Artist.create!(:name => $1).id 
    end 
    self.artist_ids = ids.split(",") 
    end 

end 

# all/models/artist.rb 

class Artist < ActiveRecord::Base 

    has_many :artisanships 
    has_many :users, :through => :posts 
    has_many :posts, :through => :artisanships 
    attr_accessible :name 
end 


# app/models/artisanship.rb 

class Artisanships < ActiveRecord::Base 

    belongs_to :post 
    belongs_to :artist 
    has_one :user, :through => :post 
    attr_accessible :post_id, :artist_id 
end 

# app/views/shared/_post_form.html.erb 

<%= 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 %> # html 5 data attribute for prepopulate 
    </div> 
    <div class="actions"> 
    <%= f.submit "Submit" %> 
    </div> 
<% end %> 


# app/controllers/pages_controller.rb 

class PagesController < ApplicationController 

    def home 
    @title = "Home" 
    @featured_posts = Post.featured.limit(10) 
    if user_signed_in? 
     @user = current_user 
     @post = current_user.posts.build 
     @feed_items = current_user.feed.paginate(:per_page => "10", :page => params[:page]) 
    else 
    #render :layout => 'special_layout' 
    end 
    end 

# app/controllers/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 
end 

# app/controller/artists_controller.rb 

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 

    def show 
    @artist = Artist.find(params[:id]) 
    end 

    def new 
    @artist = Artist.new 
    end 

    def create 
    @artist = Artist.build(params[:artist]) 
    if @artist.save 
     redirect_to @artist, :notice => "Successfully created artist." 
    else 
     render :action => 'new' 
    end 
    end 

    def edit 
    @artist = Artist.find(params[:id]) 
    end 

    def update 
    @artist = Artist.find(params[:id]) 
    if @artist.update_attributes(params[:artist]) 
     redirect_to @artist, :notice => "Successfully updated artist." 
    else 
     render :action => 'edit' 
    end 
    end 

    def destroy 
    @artist = Artist.find(params[:id]) 
    @artist.destroy 
    redirect_to authors_url, :notice => "Successfully destroyed artist." 
    end 

end 

答えて

1

1)アーティストはActiveRecordを継承するクラスです。クラスメソッドcreateを呼び出すと、データベースで設定したさまざまなフィールドを受け入れ、レコードの保存を試みます。結果のオブジェクトを返します。モデルにバリデーションがあり、オブジェクトがそれらを渡さない場合、createはレコードを保存しないことに注意してください。

2)いいえ、コントローラはまったく触れられません。コントローラは、アプリケーションがurlリクエストにどのように反応するかを指定する場所で使用されます。 artist#createはurl/artistへのPOST要求に応答します。作成アクションでは、そのリクエストが来たときに何をしたいのかを簡単に指定できます。この場合、投稿されたデータをアーティストとしてデータベースに保存します。

3)これは#2で答えられましたが、ここではどのように動作するのですか。 URLがサーバにヒットすると、Railsはあなたのルートをチェックし、どこに行くのかを判断します。次に、コントローラ内のコードを呼び出します。いずれかのモデルが呼び出されると、そのモデルでコードが実行されます。リダイレクトや何かをしないと、適切なビューが実行され、アクション内で宣言されたすべてのインスタンス変数が使用可能になります。

これがあなたのためにクリアされることを願っています。 :)

関連する問題