Я использую API Tumblr для размещения всех сообщений в блоге. Это мой индексный метод в контроллере:передать значение из формы в переменную переменной
def index
# Keys given from Tumblr API
@key = '[my key]'
@secret = '[my secret]'
@oauth_token = '[my oauth token]'
@oauth_token_secret = '[my oauth token secret]'
# Sets the client that allows interfacing with Tumblr
@client = Tumblr::Client.new(
:consumer_key => @key,
:consumer_secret => @secret,
:oauth_token => @oauth_token,
:oauth_token_secret => @oauth_token_secret
)
# Make the request
@blog = "[blogname].tumblr.com"
@posts = @client.posts(@blog, :type => "photo")["posts"] #gets a posts array
# @posts = Kaminari.paginate_array(@posts["posts"]).page(params[:page]).per(10)
# # Photography posts only (other types follow the same pattern)
# @photoPosts = @myClient.posts("YOURTUMBLR.tumblr.com",
# :limit => 5,
# :type => "photo")
# @photoPosts = @photoPosts["posts"]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
Все это работает отлично. Тем не менее, я хочу, чтобы «@blog» был динамическим. Итак, в представлении мне нужна форма, в которой пользователь может вводить блог tumblr. Я просто не знаю, как соединить эти два. У кого-нибудь появилась идея?
Спасибо!
РЕДАКТИРОВАТЬ Контроллер:
class BlogController < ApplicationController
def index
@blog = "#{params[:blogname]}.tumblr.com"
end
def show
# Keys given from Tumblr API
@key = '[my key]'
@secret = '[my secret]'
@oauth_token = '[my oauth token]'
@oauth_token_secret = '[my oauth token secret]'
# Sets the client that allows interfacing with Tumblr
@client = Tumblr::Client.new(
:consumer_key => @key,
:consumer_secret => @secret,
:oauth_token => @oauth_token,
:oauth_token_secret => @oauth_token_secret
)
# Make the request
@posts = @client.posts(@blog, :type => "photo")["posts"]
respond_to do |format|
format.html # index.html.erb
format.json { render json: @posts }
end
end
end
index.html.erb:
<%= form_tag(method: "get", url: "blog") do %>
<%= text_field_tag(:blogname) %>
<%= submit_tag %>
<% end %>
show.html.erb:
<section class="section section_grid has_no-pad">
<h1 class="is_white is_bold is_uppercase"><%= p @posts.first["blog_name"] %></h1>
<ul class="s-grid-2 has_isotope">
<% @posts.each do |post| %>
<% @type = post["type"] # the type of post %>
<% @url = post["post_url"] # the url for the post %>
<% if @type == "photo" %>
<% @pictures = post["photos"] %>
<% @pictures.each do |pic| %>
<% @pic_url = pic["original_size"]["url"] %>
<li>
<%= image_tag(@pic_url) %>
</li>
<% end %>
<% end %>
<% end %>
</ul>
</section>
маршруты:
Prefix Verb URI Pattern Controller#Action
blog_index GET /blog/index(.:format) blog#index
root GET/ blog#index
Мне удалось получить форму. Я поместил @blog в метод 'index', а остальное - в метод 'show'. Я не знаю, как связать все это вместе. Между прочим, нет БД. Любой способ показать мне, как я могу собрать все это вместе? Благодаря! – Luc
Если я правильно понял, у вас есть тег формы в действии show и хотите отправить его, чтобы отобразить блог в действии индекса? что потребует от вас добавления правильного URL-адреса в форму. помощники путей должны сделать это простым в зависимости от того, как ваш контроллер называется 'form_tag method:: get, url: controller_name_path'. см. «rake routes», чтобы узнать правильное имя пути. – phoet
На самом деле это наоборот. У меня есть form_tag в моем индексе и хочу что-то сделать с результатом результата в шоу. Я отредактировал мой вопрос выше, чтобы показать вам, где я сейчас. – Luc